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

2 次查看(过去 30 天)
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 个评论
Rik
Rik 2017-6-14
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.

请先登录,再进行评论。

回答(1 个)

Star Strider
Star Strider 2017-6-14
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 个评论
Garima Sharma
Garima Sharma 2017-6-15
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 2017-6-15
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.

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by