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 does not consistently understand ~ as the user home directory. We have been complaining to the Mathworks about this for over a decade, but 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('USERPROFILE');
    else %linux,mac
        h = getenv('HOME');
    end
end

hdir = h;  % for Matlab

end