MATLAB: How can I use a variables value in another variables name?

独自空忆成欢 提交于 2019-12-17 16:53:11

问题


I am wondering if this is possible. My code looks like this:

indexStop = find(firstinSeq(x,4) ~= ...
                 littledataPassed(y:length(littledataPassed),4), 1, 'first');
for z= 0:(n-1)
   indexProcess = find((littledataPassed(y:y+indexStop-1,6) == 1 & ... 
      littledataPassed(y:y+indexStop-1,2) == firstinSeq(x,2) & ... 
      littledataPassed(y:y+indexStop-1,5) == z), 1, 'first'); 
   if isempty(indexProcess)
      msgLength[n](countmsgLength[n],:)= [firstinSeq(x,:) [0 0 0 0 0 0]];
   else
      msgLength[n](countmsgLength[n],:)= [firstinSeq(x,:) ...
         littledataPassed(y+indexProcess-1,:)];
   end
   countmsgLength[n]= countmsgLength[n] + 1;
end

I am hoping to have everywhere that reads [n] be switched to the actual value of n, such that I could use this to add data to nine different variables in the format msgLength#. I have tried searching tutorials and what not but haven't seen anything on the topic.


回答1:


It's almost always better to use arrays or cell arrays to store data than to create a bunch of variables named a1, a2, a3, etc. For example, you can initialize msgLength as a cell array with n elements:

msgLength = cell(1,n);

And you can access cells of msgLength using curly braces:

msgLength{n} = ...  %# Assign something to cell n

Your variable countmsgLength can just be a regular numeric array, since it appears to only store n values. You would just have to change the square brackets to parentheses (i.e. [n] to (n)).


However, if you really want to create n separate variables, you will likely end up using the EVAL function. This question and this question show some examples of how to create variables names using the value of another variable.




回答2:


If you absolutely have to use multiple variables, structure dynamic fieldnames using () notation would be handy. If you enter the following:

>> n = 1;
>> data.(sprintf('msgLength%u', n)) = [1 2 3 4];
>> n = 2;
>> data.(sprintf('msgLength%u', n)) = [5 6 7 8];

You'll get a structure with two fields:

>> data
data = 
   msgLength1: [1 2 3 4]
   msgLength2: [5 6 7 8]

Despite this, I second gnovice's suggestion of using an array to store data instead of several variables. You could simply add another dimension to msgLength so line 7 becomes:

msgLength(n,countmsgLength(n),:)= [firstinSeq(x,:) [0 0 0 0 0 0]];


来源:https://stackoverflow.com/questions/3346178/matlab-how-can-i-use-a-variables-value-in-another-variables-name

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