Get user home directory in Matlab on Windows

The tilde “~” character is used by most terminal shells as shorthand for the user home directory. The home directory is typically a safer place to write files than the system root directory, so ~ give a convenient way to refer to an absolute path generic across systems. Many code languages require parsing the tilde, including Python, C++, Fortran and Matlab. GNU Octave understands that ~ tilde is the user’s home directory on any operating system, even Windows. Matlab does not consistently understand ~ as the user home directory, particularly on Windows.

To fix this issue, we created expanduser.m

stdlib.expanduser('~/Downloads/foo')
OS expanded
Linux /home/user/Downloads/foo
Windows C:\users\user\Downloads\foo
macOS /Users/user/Downloads/foo

Python

Python paths starting with ~ need pathlib.Path('~/mypath').expanduser() function to expand this into the user directory.

import pathlib
pathlib.Path('~/Downloads/foo').expanduser()