How do I average columns in cell array if some cells are empty?

조회 수: 4 (최근 30일)
lil brain
lil brain 2022년 12월 12일
편집: Voss 2022년 12월 13일
Hi,
I have a cell array called new_mat. I would like to compute the mean of all the values in each column and save the result in a new array called averages. I would then have a numerical array with one row and five columns, so five values in total.
One of my columns however contains an empty cell which I think is causing an error.
I have tried this:
averages = cellfun(@(x) mean(x, 1), new_mat);
But I get this error:
Error using cellfun
Non-scalar in Uniform output, at index 24, output 1.
Set 'UniformOutput' to false.
What am I doing wrong?

답변 (2개)

Arif Hoq
Arif Hoq 2022년 12월 12일
you are asking the same question several times. your cell array "new_mat". giving an answer to your previous question:
a=load("split_newdata_mean.mat");
b=a.split_newdata_mean;
b{1,4}=[b{1,4};NaN]; % making equal dimension in the 4th column
c=[b{:}];
new_mat=c';
averages=mean(new_mat)
averages = 1×5
24.4539 30.7694 29.0602 12.3292 NaN
  댓글 수: 1
Arif Hoq
Arif Hoq 2022년 12월 12일
편집: Arif Hoq 2022년 12월 12일
the average of the 5th column is NaN. If you want it as a numerical then add 0 or any value in the 4th column of the cell array.
a=load("split_newdata_mean.mat");
b=a.split_newdata_mean;
b{1,4}=[b{1,4};0]; % making equal dimension in the 4th column
c=[b{:}];
new_mat=c';
averages=mean(new_mat)
averages = 1×5
24.4539 30.7694 29.0602 12.3292 5.0537

댓글을 달려면 로그인하십시오.


Voss
Voss 2022년 12월 13일
편집: Voss 2022년 12월 13일
load new_mat
new_mat % notice the cell in the 4th row, 5th column contains an empty array
new_mat = 5×5 cell array
{[ 2.9473]} {[ 0.7736]} {[24.7335]} {[-32.1028]} {[ 5.4609]} {[ 7.9357]} {[15.6115]} {[28.3915]} {[ 51.8624]} {[ 1]} {[38.3376]} {[62.5463]} {[35.4955]} {[ 17.6059]} {[ 35.9168]} {[15.0732]} {[24.9668]} {[ 3.2505]} {[-21.6557]} {0×0 double} {[57.9756]} {[49.9486]} {[53.4301]} {[ 45.9361]} {[-17.1092]}
n_col = size(new_mat,2);
averages = zeros(1,n_col);
for ii = 1:n_col
averages(ii) = mean([new_mat{:,ii}]);
end
disp(averages);
24.4539 30.7694 29.0602 12.3292 6.3171

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by