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

user379362 picture user379362 · Jun 29, 2010 · Viewed 15.7k times · Source

I need to calculate the mean, standard deviation, and other values for a number of variables and I was wondering how to use a loop to my advantage. I have 5 electrodes of data. So to calculate the mean of each I do this:

mean_ch1 = mean(ch1);  
mean_ch2 = mean(ch2);  
mean_ch3 = mean(ch3);  
mean_ch4 = mean(ch4);  
mean_ch5 = mean(ch5);  

What I want is to be able to condense that code into a line or so. The code I tried does not work:

for i = 1:5  
  mean_ch(i) = mean(ch(i));  
end

I know this code is wrong but it conveys the idea of what I'm trying to accomplish. I want to end up with 5 separate variables that are named by the loop or a cell array with all 5 variables within it allowing for easy recall. I know there must be a way to write this code I'm just not sure how to accomplish it.

Answer

gnovice picture gnovice · Jun 29, 2010

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