Search code examples
matlabfor-loopmat-file

Matlab: How to save num2str(i).mat in matlab?


Suppose I have a for loop and want to save a mat file at each iteration with the name of the iteration. I made it as below but it does not work.

clc;
clear;
for i=1:3
    filename=num2str(i);
    save(filename,'.mat')
end

Solution

  • The first input to save needs to be a string, you're passing two inputs to save (filename and '.mat'). save has no way of automatically combining your filename with the .mat extension you've provided and instead ends up looking for a variable named '.mat' which is obviously going to result in errors.

    You want to concatenate these two strings into one string (using [] or strcat) and pass this as the first input to save.

    save([filename, '.mat'])
    

    Alternately, you could just provide filename because the .mat extension will automatically be appended assuming that filename doesn't already have an extension. Personally, I don't particularly like this method as I use . in my filenames, but if you don't this would likely work.

    save(filename)