How do I convert to nan all entries with a particular value in a cell array?

1 view (last 30 days)
Each entry of the cell array is a matrix, and I want to convert to nan all entries, say, of value=1. Something like this: a=cellfun(@(x) x(x==1)=nan, a, 'un',0)
I tried to do this by creating a separate function, but I need to delete different values from the matrix assigned to each cell in the cell array, so I'm not sure how that would work. Can I just define a cell function like this?
function out = replaceval(in, val)
in(in==val) = NaN;
out = in;
end
  1 Comment
Rik
Rik on 14 Jun 2017
This should work as far as I can tell. Keep in mind that you might have to replicate your second input as a cell if it is not the same for the cell you are using as first input.

Sign in to comment.

Answers (1)

Star Strider
Star Strider on 14 Jun 2017
I could not get this to work with only cellfun calls, and needed to use a loop.
This works:
C = {randi(9,5), randi(9,5), randi(9, 5)}; % Create Data
L = cellfun(@(x) x == 1, C, 'Uni',0); % Logical Arrays
C1 = C{1} % Display Initial Values
L1 = L{1} % Display Logical Arrays
for k1 = 1:size(C,2)
C{k1}(L{k1}) = NaN; % Replace With ‘NaN’
end
New_C1 = C{1} % Display Replaced Values
C1 =
2 4 9 3 5
1 8 1 3 7
4 5 2 3 4
5 3 7 6 1
6 5 7 6 8
L1 =
5×5 logical array
0 0 0 0 0
1 0 1 0 0
0 0 0 0 0
0 0 0 0 1
0 0 0 0 0
New_C1 =
2 4 9 3 5
NaN 8 NaN 3 7
4 5 2 3 4
5 3 7 6 NaN
6 5 7 6 8
Remove the ‘Display’ lines. They exist only to demonstrate the results.
  2 Comments
Garima Sharma
Garima Sharma on 15 Jun 2017
Actually, this worked for me. I just have to make sure that the 2 cell arrays from which in and val are pulled have the same dimension.
B=cellfun(@replaceval, a, b, 'un',0)
function out = replaceval(in, val)
in(in==val) = NaN;
out = in;
end
Star Strider
Star Strider on 15 Jun 2017
In my code, the logical cell arrays ‘L’ will by definition have the same dimensions as the matrices they are derived from. That is the advantage of calculating them in a separate step.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!