Niels Møller
Niels Møller

Reputation: 203

Mean value of multiple columns

I have searched a lot to find the solution, but nothing really works for me I think.

I have n data files containing two columns each (imported using uigetfile). To extract the data, I use a for loop like this:

for i=1:n
    data{i}=load(filename{i});
    x{i}=data{i}(:,1);
    y{i}=data{i}(:,2);  
end

Now, I want to get the mean value for each row of all the (let's say) x-values. E.g.:

x{1} = [1,4,7,8]

x{2} = [1,2,6,9]

Then I want something like

x_mean = [1,3,6.5,8.5]

I have tried (where k is number of rows)

for i=1:n
        data{i}=load(filename{i});
        x{i}=data{i}(:,1);
        y{i}=data{i}(:,2);  
    j=1:k
        x_mean=sum(x{i}(j))/n
end

But I can't use multiple counters in a for loop (as I understand). Moreover, I don't use mean as I don't see how I can use it in this case.

If someone could help me, it would be great!

Upvotes: 0

Views: 2111

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

You can capture the contents of each numeric array in the cell x into a new numeric array x_num like so:

x_num = [x{:}]

Computing the mean is then as simple as

mean_x = mean( [x{:}] )

For your example, that gives you the mean of all numbers in all arrays in x, which will therefore be a scalar.

If you want to compute the mean of all the rows (column-wise mean), as your example would indicate), you have to concatenate your arrays vertically, which you can do with cat:

mean_x_columnwise = mean( cat(1,x{:}) )

If you want to take the mean over all the columns (row-wise mean), you should only have to tell mean that you are looking at a different dimension:

mean_x_rowwise = mean( cat(1,x{:}), 2)

Upvotes: 3

Related Questions