Filter löschen
Filter löschen

For loop through cell arrays

91 Ansichten (letzte 30 Tage)
Ali Yilmaz
Ali Yilmaz am 23 Jun. 2020
Kommentiert: Ali Yilmaz am 25 Jun. 2020
I have a 1×4 cell array of
{60×4 double} {60×4 double} {60×4 double} {60×4 double}
and I need to;
-find the values at the 3rd column at the rows have "20" at the first column in each cell
-then eliminate zeros if there is any
-then take average
As an illustration
10 NaN 0 NaN 20 NaN 623 1
10 NaN 0 NaN 20 NaN 0 NaN
20 NaN 310 1 10 NaN 38 1
20 NaN 0 NaN 10 NaN 0 NaN
20 NaN 1445 1 10 NaN 0 NaN
the first cell should give the average of 310 and 1445, whereas the second cell should give 623.
I am thinking of a for loop but I couldnt make it work. Thanks in advance!
  3 Kommentare
Ali Yilmaz
Ali Yilmaz am 23 Jun. 2020
Hi Adam,
Honestly I deleted my version as it was not even close to what I need. I'll be glad if you can share your version.
Thanks and regards
Adam Danz
Adam Danz am 25 Jun. 2020
See answer below.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Adam Danz
Adam Danz am 24 Jun. 2020
Bearbeitet: Adam Danz am 25 Jun. 2020
If you want to do this in a loop, there are 4 steps I've outlined below.
"c" is the 1x4 cell array.
column3Means = nan(size(c));
for i = 1:numel(c)
% Find rows where column 1 equals 20
index1 = c{i}(:,1) == 20;
% Find rows where column 3 is not 0
index2 = c{i}(:,3) ~= 0;
% Combine those indices
idx = index1 & index2;
% Use the combined index to compute the mean
column3Means(i) = mean(c{i}(idx,3),'omitnan');
end
FYI, the loop can be avoided using the cellfun() function.
  10 Kommentare
Adam Danz
Adam Danz am 25 Jun. 2020
Glad it worked out.
The take-home message is: learn/use indexing.
Indexing is a superpower of Matlab. My answer uses logical indexing but there are other types of indexing as well.
Ali Yilmaz
Ali Yilmaz am 25 Jun. 2020
Thank you so much again, I will definitely go throuh the link you've shared.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by