given cell array 'cell1', create new cell array 'cell2' with elements of cell1 containing string 'f' and ages >=30 && <=40
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
James Hong
am 7 Okt. 2020
Bearbeitet: Stephen23
am 8 Okt. 2020
cell1={'name' 'gender' 'age'; ...
's1' 'f' 25; ...
's2' 'm' 35; ...
's3' 'f' 30; ...
's4' 'm' 22; ...
's5' 'f' 38}
cell2={};
for the conditions given above, cell2 should be:
cell2={'s3' 'f' 30; ...
's5' 'f' 38}
How to I search through cell array cell1 and add rows to cell array cell2 containing string 'f' and ages >=30 && <=40?
I know how to cell2mat or cell2table and work with the matrix -- the problem is that the output should also be a cell array ... so I would like to avoid converting to a matrix or table.
0 Kommentare
Akzeptierte Antwort
Stephen23
am 7 Okt. 2020
Bearbeitet: Stephen23
am 7 Okt. 2020
age = vertcat(cell1{2:end,3});
ix1 = age>=30 & age<=40;
ix2 = strcmp('f',cell1(2:end,2));
cell2 = cell1([false;ix1&ix2],:)
Giving:
cell2 =
's3' 'f' [30]
's5' 'f' [38]
2 Kommentare
Stephen23
am 8 Okt. 2020
Bearbeitet: Stephen23
am 8 Okt. 2020
"Where would I find the mathworks original documentation that explains how 'false' works in this context?"
"I understood ix1 and ix2 to be conditional statements to extract relevant rows."
ix1 and ix2 are actually logical vectors, which can be used for logical indexing (one of the most basic and powerful types of MATLAB indexing):
Because the first row of cell1 has non-scalar character vectors which would cause problems for the concatenation, the first row is excluded from the logical comparison and strcmp. Therefore both ix1 and ix2 have size 5x1. These are ANDed together, and then false is concatenated on top to give a logical vector of size 6x1, which is used to selected the required rows from cell1.
cell1([false;ix1&ix2],:)
ix1&ix2 % AND(ix1,ix2) -> 5x1 logical vector
[false; ] % -> 6x1 logical vector
cell1( ,:) % use logical vector to select rows
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Cell Arrays 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!