-1

I try to load a .mat file in MATLAB R2016a. However, when I make the filename variable, it fails with

Error using load Unable to read file 'filename'. No such file or directory.

The documentation for R2018a states that the filename has to be

specified as a character vector or string

which i did. I searched for similar questions on SO, but they were all due to typing errors, e.g. Error using load; Unable to read file matlab

Code for reproduction:

clear all
mat1 = magic(5);
save mat1
clear mat1
load mat1 % working
clear mat1
filename = 'mat1.mat'; % tried with/without .mat
load filename % not working
  • What is the cause of this error?
  • How to resolve it?
David
  • 85
  • 7
  • Could the down-voters please give a reason? It took me some time to figure this out; it was not answered here before; it is encouraged to answer own questions: https://stackoverflow.com/help/self-answer – David Jun 29 '18 at 10:55
  • I didn’t downvote, but this same question has been asked very often. – Cris Luengo Jun 29 '18 at 12:26
  • Another one: https://stackoverflow.com/q/13692907/7328782 – Cris Luengo Jun 29 '18 at 12:33
  • Thanks for the response. I must have used the wrong search terms for not finding the first two examples. The third one seems to be a different problem. – David Jun 29 '18 at 12:48

2 Answers2

1

After further research I found that the documentation (R2018a) also states

load filename is the command form of the syntax. [...] Do not use command form when any of the inputs, such as filename, are variables.

This answers my second question. Use:

load(filename)
David
  • 85
  • 7
1

The cause of this error is that the statement:

load filename

internally evaluates to:

load('filename.mat')

in order to support command-form statements statements like load mat1 in your example. It fails because the file filename.mat clearly does not exist.

The function form is always safer, in my opinion.

loudmummer
  • 544
  • 3
  • 19