Matlab:for loop和sprintf组合

时间:2018-02-13 14:06:02

标签: matlab loops for-loop

我有以下数据:

no_gridpoints = 640                                   % amount of columns in considered
surfaceelevation                                      % a 1x640 array with surface elevation
Terskol1752, Terskol1753, ... Terskol2017             % 365x1 arrays with daily mean temperatures for 1 year of which the fifth colomn contains the temperature data

我想在文件名中创建具有相应年份的temp_glacier文件。通过在循环中使用sprintf命令,可以循环使用所有年份(1752-2017):

for k = 1752:2017
    for m = 1:no_gridpoints
    sprintf('temp_glacier%d(m)',k) = sprintf('Terskol%d(:,5)',k) + surfaceelevation
    end
end

但是,我总是收到错误'Subscripted assignment dimension mismatch'。谁能告诉我我做错了什么?

由于

1 个答案:

答案 0 :(得分:2)

如我的评论中所述:您似乎错误地sprintf evalsprintf中的表达式未被评估,因此您的赋值是声明“将此字符串=此另一个字符串添加到数组中” - 这没有任何意义。

要按原样纠正您的代码,您可以执行以下操作

for k = 1752:2017
    for m = 1:no_gridpoints
    eval(sprintf('temp_glacier%d(m) = Terskol%d(:,5) + surfaceelevation', k, k))
    end
end 

这是个坏主意

将您的年度数据存储在单个单元格数组中(或者因为它的数字和大小相同,只是标准矩阵)而不是266个单独命名的变量,这样会更好。我说更好的练习,因为如果你想使用eval,你应该知道it should be avoided

此方法如下所示:

Terskol = [ ... ] % your data here, in a 266*365 matrix where each row is a year
for k = (1752:2017) - 1751 % We actually want to loop through rows 1 to 266
    for m = 1:no_gridpoints
        % Your arrays were 1D, so you were originally getting a scalar temp val
        % We can do that here like so...
        temp_glacier(m) = Terskol(k, 5) + surfaceelevation; 
        % Now do something with temp_glacier, or there was no point in this loop!
        % ...
    end
end 

矢量化内循环:

for k = (1752:2017) - 1751 % We actually want to loop through rows 1 to 266
    temp_glacier = repmat( Terskol(k, 5) + surfaceelevation, 1, no_gridpoints );     
    % Do something with temp_glacier...
end