Remove values from cell array based on condition

21 ビュー (過去 30 日間)
lucksBi
lucksBi 2017 年 8 月 16 日
コメント済み: lucksBi 2017 年 8 月 16 日
Hey
I have two cell arrays like this:
A= {[2,3,4,5,6]; [1,3,4,5,6,7,8] }
B= {NaN, 1,1,-0.9,0.8,[],[]; NaN, NaN, 0.9,-1,NaN,0.8,0.2}
I want to find indexes of values less than 0 and of NaN values in B like here in first row of B we will get 1 (for NaN) and 4 for (values less than zero) and for these indexes i want to remove values placed in A like value at index 1 in A is 2 so it will be removed and also 5 will be removed. Same for row 2. New matrix A will look like this:
NewA= {[3,4,6]; [4,7,8]}
Please help.

採用された回答

Guillaume
Guillaume 2017 年 8 月 16 日
I can't help but feel that you're doing something very wrong if you want to do what you're asking. Your problem is very ill-defined: your A is a 2x1 cell array, your B is a 2x7 cell array, so you're asking to match column indices of cell array B with column indices of the contents of column 1 of A. That does not sound right.
Furthermore, what happens if a NaN or negative number occurs at an index larger than the number of columns in the corresponding A cell?
One way to do what you want:
tokeep = num2cell(cellfun(@(c) isempty(c) || (~isnan(c) && c>=0), B), 2);
newA = cellfun(@(a, keep) a(keep(1:numel(a))), A, tokeep, 'UniformOutput', false)
This will do what you want but as said, it does sound like something in your logic is broken.
  1 件のコメント
lucksBi
lucksBi 2017 年 8 月 16 日
No values in B are also based on A using some mathematics so logic is correct in this case. Thanks for helping.

サインインしてコメントする。

その他の回答 (1 件)

José-Luis
José-Luis 2017 年 8 月 16 日
A= {[2,3,4,5,6]; [1,3,4,5,6,7,8] }
B= {NaN, 1,1,-0.9,0.8,[],[]; NaN, NaN, 0.9,-1,NaN,0.8,0.2}
result = cell(size(A));
dummy = cellfun(@(x) ~isempty(x) && ~isnan(x) && x >= 0 ,B,'UniformOutput', false);
for ii = 1:size(A,1)
result{ii} = A{ii}([dummy{ii,:}])
end
  1 件のコメント
lucksBi
lucksBi 2017 年 8 月 16 日
This also works. Thankyou so much for your answer.

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by