【问题标题】:Matlab: for loop and sprintf combinationMatlab:for循环和sprintf组合
【发布时间】:2018-02-14 00:14:59
【问题描述】:

我有以下数据:

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

但是,我总是收到错误消息“下标分配维度不匹配。”。谁能告诉我我做错了什么?

谢谢

【问题讨论】:

  • 您似乎将sprintf 误认为evalsprintf 中的表达式没有被评估,所以你的任务是声明“使这个字符串=这个另一个字符串添加到一个数组中”——这没有任何意义。将年度数据存储在单个单元格数组而不是 266 个单独命名的变量中会是更好的做法,然后您可以轻松地操作它们。我说更好的做法是因为如果你要使用eval,你应该知道it should be avoided
  • Wolfie 的评论是对的。而且很难知道你真正在寻找什么。您想用数据创建文本文件(例如逗号分隔)吗?还是 Matlab .mat 文件?我知道你想要一个包含那一年温度的每一年的单独文件。但是你如何处理“+surfaceelevation”部分?

标签: matlab loops for-loop


【解决方案1】:

正如我在评论中所述:您似乎将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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2021-03-20
    相关资源
    最近更新 更多