Remove values from cell array based on condition

조회 수: 2 (최근 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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by