0

I have a cell with different columns as follow:

M =

[1x16 double]
[1x17 double]
[1x17 double]
[1x17 double]
[1x17 double]
[1x17 double]
[1x17 double]
[1x17 double]
[1x17 double]
[1x16 double]
[1x18 double]
[1x17 double]
[1x16 double]
[1x16 double]
[1x13 double]
[1x21 double]
[1x15 double]
[1x17 double]
[1x17 double]
[1x17 double]
[1x16 double]
[1x16 double]
[1x16 double]
[1x17 double]
[1x17 double]

I am looking to take an average looking like mean(M,1). Is it possible to do it using MATLAB?

Thanks

Julliette
  • 27
  • 1
  • 4
  • 1
    If you use the solution in the duplicate to put the values into an array, you can then use `nanmean(M,1)` to get the mean. – beaker May 30 '17 at 15:38

1 Answers1

1

If you want to mean all the values, you can run the following command:

mean(cell2mat(M))

cell2mat transfer M to a matrix with dimensions of 1xn which n is the number of all values in M, then mean function get the average of the all values.

Also, if you want to get means for each cell you can run the following:

cellfun(@mean,M)

this will get the mean for each matrix in each cell.

Update

As the size of columns are not the same, to get the mean of each column, we can do like the following:

m = max(cellfun(@length,M)); // get the max length of the matrices
for i = 1 : length(M)
    M{i}(m+1) = 0
end
// mean of each column
means = mean(reshape(cell2mat(M), length(M), m + 1));
% in octav: 
% means = mean(reshape(cell2mat(M), m + 1, length(M))');
means = means(1:m);

For more details, first we resize all arrays into the same size. After that, merge them into a matrix using cell2mat, and remove the extra column which was added to facilitate our computation.

Community
  • 1
  • 1
OmG
  • 18,337
  • 10
  • 57
  • 90
  • Thank you for your answer. I am in doubt that I can use mean(cell2mat(M)) because I need to have the same column for each cell and if I do so It gives me the error "Dimensions of matrices being concatenated are not consistent " – Julliette May 30 '17 at 13:36
  • I want to have the mean of all first columns and so on till the end, the solution that you provided to me only calculate the mean for each cell. – Julliette May 30 '17 at 13:57
  • I run your code for a simple exmaple , i expected the average of first four coulm would be 2 3 4 5 respectively. but it did not work: v1 = [2 3 4 5]; v2 = [2 3 4 5 6 7]; v3= [2 3 4 5 6 7]; M={v1,v2,v3} m = max(cellfun(@length,M)); %% get the max length of the matrices for i = 1 : length(M) M{i}(m+1) = 0 end %// mean of each column means = mean(reshape(cell2mat(M), length(M), m + 1)); means = means(1:m); result: 3.0000 1.6667 1.6667 5.0000 3.0000 4.0000 ..for me the code output is not what I expected. – Julliette Jun 06 '17 at 15:02
  • @Julliette I think you use octav. anyhow, I've update my solution. You should replace `means` with this: `means = mean(reshape(cell2mat(M), m + 1, length(M))');` – OmG Jun 06 '17 at 17:46