Get user home directory in Matlab on Windows

GNU Octave understands that ~ tilde is the user’s home directory on any operating system, even Windows. Matlab, even though R2019a is not that smart. Matlab does not consistently understand ~, and I have been complaining to the Mathworks about this for over a decade, and still the Mathworks is saying WONTFIX.

For our work, we create a homepath.m that works for GNU Octave and Matlab on Linux, Mac and Windows. It returns the absolute path of the user home directory, for example:

  • Linux: /home/username
  • MacOS: /Users/username
  • Windows: C:\Users\Username

file “homepath.m” contains:

function hdir = homepath()

persistent h;

if isempty(h)
    if ispc % windows
        h = [getenv('HOMEDRIVE'),getenv('HOMEPATH')];
    else %linux,mac
        h = getenv('HOME');

hdir = h;  % for Matlab