在循环中更改变量名称 [英] Changing variable name in loop
问题描述
这是对我的问题的继续从现有矩阵中提取矩阵
现在,我用代码 (不正确!)分隔这些矩阵
for i = 3:-1:0
mat = m((sum((m == 0),2)== i),:)
end
以上部分是对原始问题的更新
我想相应地命名它,比如
mat1
mat2
mat3
mat4
任何人都可以建议一个简单的方法吗?
继续使用@Jonas和@ Clement-J。 c $ c> struct s:
N = 10; %矩阵的数量
cell_mat = cell(1,N); %预先分配(良好做法)
对于ii = 1:10
cell_mat {ii} = rand(ii); %为mat生成一些矩阵
struct_mat。(sprintf('mat%d',ii))= rand(ii);
end
这个结构很棒(带变量字段名称)可以 ,你将在 save < code $ it
-file!很酷!
$ b $ save('myMatFile.mat','struct_mat','-struct');
mat1
,..., mat10
>垫
一些很好的编码习惯:
- i 和
j
作为循环变量(或作为变量),因为它们被Matlab用作sqrt(-1)
。 -
为什么有变量名称的变量?你需要有一个非常好的理由!请描述你正在努力达到的目标,我相信你会在这里得到更好,更优雅的解决方案... ... $ / $>
This is in continuation to my question Extract matrix from existing matrix
Now I am separating these matrices by the code (Not correct !)
for i = 3:-1:0
mat = m((sum((m == 0), 2)==i),:)
end
The above part is an update to my original question
I want to name it accordingly, like
mat1
mat2
mat3
mat4
Can anybody suggest an easy method to it?
Following @Jonas and @Clement-J.'s proposals, here is how toy use cell
s and struct
s:
N = 10; % number of matrices
cell_mat = cell(1, N); % pre allocate (good practice)
for ii = 1 : 10
cell_mat{ii} = rand( ii ); % generate some matrix for "mat"
struct_mat.( sprintf( 'mat%d', ii ) ) = rand( ii );
end
Nice thing about the struct (with variable field names) is that you can save
it
save( 'myMatFile.mat', 'struct_mat', '-struct');
and you'll have variables mat1
,...,mat10
in the mat
-file! Cool!
Some good coding practices:
Pre-allocate matrices and arrays in Matlab. Changing a variable size inside a loop really slows down Matlab.
Do not use
i
andj
as loop variables (or as variables at all) since they are used assqrt(-1)
by Matlab.Why having variables with variable names? You need to have an extremely good reason for doing this! Please describe what you are trying to achieve, and I'm sure you'll get better and more elegant solutions here...
这篇关于在循环中更改变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!