在循环中更改变量名称

在循环中更改变量名称

本文介绍了在循环中更改变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 这是对我的问题的继续从现有矩阵中提取矩阵 现在,我用代码 (不正确!)分隔这些矩阵 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 $ b $ save('myMatFile.mat','struct_mat','-struct'); ,你将在 mat1 ,..., mat10 >垫 -file!很酷! 一些很好的编码习惯: i 和 j 作为循环变量(或作为变量),因为它们被Matlab用作 sqrt(-1)。 为什么有变量名称的变量?你需要有一个非常好的理由!请描述你正在努力达到的目标,我相信你会在这里得到更好,更优雅的解决方案... ... $ / $> This is in continuation to my question Extract matrix from existing matrixNow I am separating these matrices by the code (Not correct !)for i = 3:-1:0 mat = m((sum((m == 0), 2)==i),:)endThe above part is an update to my original questionI want to name it accordingly, likemat1mat2mat3mat4Can 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 matricescell_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 );endNice thing about the struct (with variable field names) is that you can save itsave( '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 and j as loop variables (or as variables at all) since they are used as sqrt(-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... 这篇关于在循环中更改变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-21 12:16