带零填充数字的 Matlab 文件名 [英] Matlab file name with zero-padded numbers
问题描述
我有 11x11 矩阵,我将它们保存为 .mat
文件,从 F01_01
到 F11_11
.我必须在每个文件上运行一个函数 Func
.由于时间长,想写个脚本自动运行函数:
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
但它不起作用,Matlab 找不到 mat 文件.
有人可以帮忙吗?
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']
评估为
F1_1.mat
而不是
F01_01.mat
正如预期的那样.
这样做的原因是 i=01
是双类型赋值,i
等于 1
- 没有前导零这些类型的变量.
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
几条评论:
注意使用
sprintf
格式化双ii
和jj
使用%02d代码>.
Note the use of
sprintf
to format the doubleii
andjj
with leading zero using%02d
.
你可以使用num2str<的第二个参数/code>
格式化其输出,例如:num2str(ii,'%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.
matlab 中更好的做法 不要使用i
和j
作为循环计数器,因为它们在matlab中的默认值为sqrt(-1)
.
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)
.
这篇关于带零填充数字的 Matlab 文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!