在循环中更改变量名称 [英] Changing variable name in loop

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

问题描述

这是对我的问题的继续从现有矩阵中提取矩阵
现在,我用代码 (不正确!)分隔这些矩阵


  for i = 3:-1:0 
mat = m((sum((m == 0),2)== i),:)
end

以上部分是对原始问题的更新

我想相应地命名它,比如

  mat1 
mat2
mat3
mat4

任何人都可以建议一个简单的方法吗?

cell s和<$>的解决方案

继续使用@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
$ b $ save('myMatFile.mat','struct_mat','-struct');

,你将在 mat1 ,..., mat10 >垫 -file!很酷!

一些很好的编码习惯:


    i 和 j 作为循环变量(或作为变量),因为它们被Matlab用作 sqrt(-1)


  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 cells and structs:

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:

  1. Pre-allocate matrices and arrays in Matlab. Changing a variable size inside a loop really slows down Matlab.

  2. Do not use i and j as loop variables (or as variables at all) since they are used as sqrt(-1) by Matlab.

  3. 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屋!

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