-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?
4
  • 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: stackoverflow.com/help/self-answer Commented Jun 29, 2018 at 10:55
  • I didn’t downvote, but this same question has been asked very often. Commented Jun 29, 2018 at 12:26
  • Another one: stackoverflow.com/q/13692907/7328782 Commented Jun 29, 2018 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. Commented Jun 29, 2018 at 12:48

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

8 Comments

Thanks for the response. However, if this is really the cause, something like filename = 'mat1';load filename (without .mat) should work - but it doesn't.
@David load filename evaluates to load('filename.mat'); not load('mat1.mat') and hence it shouldn't work.
The last sentence in the answer is opinion based though
Yeah, @SardarUsama I made a change to that sentence. But is there any situation where the command form is safer?
Right, okay. Understood.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.