Remove values from cell array based on condition

1 view (last 30 days)
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.

Accepted Answer

Guillaume
Guillaume on 16 Aug 2017
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 Comment
lucksBi
lucksBi on 16 Aug 2017
No values in B are also based on A using some mathematics so logic is correct in this case. Thanks for helping.

Sign in to comment.

More Answers (1)

José-Luis
José-Luis on 16 Aug 2017
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

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!