How can I skip empty cells when averaging during a function?

12 views (last 30 days)
Hi,
I have a function in which I average the values of the doubles within each cell of a cell array.
for i = 1:length(explained_balls)
explained_pc1_avg_part_x_phase(1,2) = mean(explained_balls{i}(1,:));
end
Unrecognized function or variable 'explained_balls'.
Because I have a cell which is empty I get the error
Index in position 1 exceeds array bounds.
I was wondering if I can write the functiion so that it skips the empty cell and doesnt throw the error? Help is greatly appreciated.

Answers (1)

Chunru
Chunru on 3 Jun 2022
load explained_balls
whos
Name Size Bytes Class Attributes ans 1x44 88 char cmdout 1x33 66 char explained_balls 1x15 3912 cell
for i = 1:length(explained_balls)
%explained_balls{i}
if isempty(explained_balls{i})
explained_pc1_avg_part_x_phase(i) = NaN; % or 0
else
% explained_pc1_avg_part_x_phase(1,2) = mean(explained_balls{i}(1,:));
% The above find average of the 1st row, which is a single number.
% Check it out!!!
explained_pc1_avg_part_x_phase(i) = mean(explained_balls{i});
end
end
explained_balls
explained_balls = 1×15 cell array
{21×1 double} {21×1 double} {21×1 double} {21×1 double} {21×1 double} {21×1 double} {21×1 double} {21×1 double} {0×0 double} {21×1 double} {21×1 double} {21×1 double} {21×1 double} {21×1 double} {21×1 double}
explained_pc1_avg_part_x_phase
explained_pc1_avg_part_x_phase = 1×15
4.7619 4.7619 4.7619 4.7619 4.7619 4.7619 4.7619 4.7619 NaN 4.7619 4.7619 4.7619 4.7619 4.7619 4.7619

Community Treasure Hunt

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

Start Hunting!