How can I create/process variables in a loop in MATLAB?

会有一股神秘感。 提交于 2019-11-28 01:32:52

You have a few options for how you can do this:

  • You can put all your channel data into one large matrix first, then compute the mean of the rows or columns using the function MEAN. For example, if each chX variable is an N-by-1 array, you can do the following:

    chArray = [ch1 ch2 ch3 ch4 ch5];  %# Make an N-by-5 matrix
    meanArray = mean(chArray);        %# Take the mean of each column
    
  • You can put all your channel data into a cell array first, then compute the mean of each cell using the function CELLFUN:

    meanArray = cellfun(@mean,{ch1,ch2,ch3,ch4,ch5});
    

    This would work even if each chX array is a different length from one another.

  • You can use EVAL to generate the separate variables for each channel mean:

    for iChannel = 1:5
      varName = ['ch' int2str(iChannel)];  %# Create the name string
      eval(['mean_' varName ' = mean(' varName ');']);
    end
    

If it's always exactly 5 channels, you can do

ch = {ch1, ch2, ch3, ch4, ch5}
for j = 1:5
    mean_ch(j) = mean(ch{j});
end

A more complicated way would be

for j = 1:nchannels
    mean_ch(j) = eval(['mean(ch' num2str(j) ')']);
end

Apart from gnovice's answer. You could use structures and dynamic field names to accomplish your task. First I assume that your channel data variables are all in the format ch* and are the only variables in your MATLAB workspace. The you could do something like the following

%# Move the channel data into a structure with fields ch1, ch2, ....
%# This could be done by saving and reloading the workspace
save('channelData.mat','ch*');
chanData = load('channelData.mat');

%# Next you can then loop through the structure calculating the mean for each channel
flds = fieldnames(chanData); %# get the fieldnames stored in the structure

for i=1:length(flds)
     mean_ch(i) = mean(chanData.(flds{i});
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!