在Matlab中保存在循环中 [英] Saving inside a loop in Matlab

查看:82
本文介绍了在Matlab中保存在循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Matlab中保存一些在每次循环迭代时创建的矩阵,这些矩阵使用的名称取决于循环索引h.更准确地说,代码是

I need to save in Matlab some matrices created at each iteration of a loop using names depending on the loop index h. More precisely, the code is

for h=1:4

   A=randn(2,1);
   B=randn(2,1);
   C=randn(2,1);

save(sprintf('data%d.mat',h),'-v7.3', 'A' , 'B', 'C')

end

对于h=3, 我得到矩阵data3,其名称取决于循环索引,其中包含矩阵A,B,C.我想以data3包含A3,B3,C3的方式修改该行代码.

for h=3, I get the matrix data3, whose name depends on the loop index, containing the matrices A,B,C. I want to modify that line of code in a way such that data3 containes A3,B3,C3.

注意:使用save(sprintf('data%d.mat',h), ['A' h], ['B' h], ['C' h] ,'-v7.3')会给出错误

Error using save
'A' is not a valid variable name.

推荐答案

您将必须使用局部函数方法(或在单独的脚本中设置变量重命名函数)以利用 inputname -function来获取子函数中的实际变量名.

You will have to use a local function approach (or set the variable-renaming-function up in a separate script) to utilize the assignin-function.
The local function is required, because you need to create the new variable in the caller workspace. (Only 'caller' and 'base' are possible inputs for assignin - and 'base' is the workspace outside the function).
In addition, you'll have to make use of the inputname-function to get the actual variable name in your subfunction.

function test_func

for h=1:4

    A=randn(2,1);
    B=randn(2,1);
    C=randn(2,1);

    assignVar(A,h)
    assignVar(B,h)
    assignVar(C,h)

    save(sprintf('data%d.mat',h),'-v7.3', ['A' num2str(h)], ...
                                          ['B' num2str(h)], ...
                                          ['C' num2str(h)])

end

end

function assignVar(Q,h)
    assignin('caller',[inputname(1) num2str(h)],Q)
end

函数assignVar具有两个参数,Qh.后者是循环计数器,前者是您要重命名的变量.您必须为三个变量中的每一个调用此函数.这将在工作区中生成称为A1A2A...的新变量,具体取决于循环计数器h的值.
现在,当您调用save时,可以使用相同的逻辑来调用这些新变量:['A' num2str(h)].请注意,您必须使用num2str来组合循环计数器的整数值和变量的字符串值.

The function assignVar takes two arguments, Q and h. The latter is the loop counter, the former the variable you want to rename. You'll have to call this for each of your three variables. This will generate new variables in your workspace, called A1 or A2 or A... depending on the value of the loop counter h.
Now, when you call save, you can call these new variables with the same logic: ['A' num2str(h)]. Note that you'll have to use num2str to combine the integer value of the loop counter and the string value of the variable.

但是,请仔细考虑使用这种方法.当您加载这些工作空间文件并要处理存储在其中的变量时,具有名为A1A2A...的变量可能被证明是一场编码梦night.

However, carefully consider using this approach. Having variables called A1, A2, A... may prove to be a coding nightmare down the line when you load those workspace files and want to process the variables stored therein.

这篇关于在Matlab中保存在循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆