given cell array 'cell1', create new cell array 'cell2' with elements of cell1 containing string 'f' and ages >=30 && <=40

1 次查看(过去 30 天)
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.

采纳的回答

Stephen23
Stephen23 2020-10-7
编辑:Stephen23 2020-10-7
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 个评论
James Hong
James Hong 2020-10-8
Could you explain the last line 'cell2=cell1([falseix1&ix2],:)? Where would I find the mathworks original documentation that explains how 'false' works in this context? There does not seem to be much on the internet about this, or my unfamiliarity with jargon hinders my web search?
I understood ix1 and ix2 to be conditional statements to extract relevant rows. Yes?
Thank you for the easy to read code.
Stephen23
Stephen23 2020-10-8
编辑:Stephen23 2020-10-8
"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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by