I have 11x11 matrices and I saved them as .mat
files from F01_01
to F11_11
.
I have to run a function Func
on each file. Since it takes a long time, I want to write a script to run the function automatically:
for i=01:11
for j=01:11
filename=['F',num2str(i), '_', num2str(j),'.mat'];
load(filename);
Func(Fi_j); % run the function for each file Fi_j
end
end
But it doesn't work, Matlab cannot find the mat-files.
Could somebody please help ?
i=01;
j=01;
['F',num2str(i), '_', num2str(j),'.mat']
evaluates to
F1_1.mat
and not to
F01_01.mat
as expected.
The reason for this is that i=01
is a double type assignment and i
equals to 1
- there are no leading zeros for these types of variables.
a possible solution for the problem would be
for ii = 1:11
for jj= 1:11
filename = sprintf('F_%02d_%02d.mat', ii, jj );
load(filename);
Func(Fi_j); % run the function for each file Fi_j
end
end
Note the use of sprintf
to format the double ii
and jj
with leading zero using %02d
.
You can use the second argument of num2str
to format its output, e.g.: num2str(ii,'%02d')
.
It is a good practice to use string formatting tools when dealing with strings.
It is a better practice in matlab not to use i
and j
as loop counters, since their default value in matlab is sqrt(-1)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With