A way to dynamically create variables in Matlab?

柔情痞子 提交于 2020-01-11 07:25:35

问题


The case I am working on is dividing a big three-dimensional array of data that I have collected using good coding practises (etc...) and now I need to segment the layers of this array into separate variables for individual processing elsewhere, I can't call my data like this BigData(:,:,n).

So I would like to create a loop where I create new variables like so

for i=1:n

createVariable('user_' i) = BigData(:,:,i);

end

How do I do this without writing n new variables by hand every time?

user_1 = BigData(:,:,1);
user_2 = BigData(:,:,2);
user_3 = BigData(:,:,3);
.
.
.

回答1:


Your disclaimer sounds convincing :-) I'll get those downvotes too. But, to be clear: using separate variables for this is bad practice.

You can use assignin to create the variables and assign them values:

for ii = 1:n
    assignin('base', ['user_' num2str(ii)], BigData(:,:,ii));
end

And yes, using separate variables for this is bad practice.




回答2:


Try using eval() - but as you said it is seen as a very bad practice. If you still want to use this, it is straight forward like:

for i = 1:n
    eval(['user_',num2str(i),' = BigData(:,:,',num2str(i),');']);
end


来源:https://stackoverflow.com/questions/24759942/a-way-to-dynamically-create-variables-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!