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

13 vues (au cours des 30 derniers jours)
lil brain le 3 Juin 2022
Réponse apportée : Chunru le 3 Juin 2022
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.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponses (1)

Chunru le 3 Juin 2022
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
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by