how to find a number in cell and make it NaN?

1 回表示 (過去 30 日間)
MP
MP 2022 年 8 月 9 日
回答済み: MP 2022 年 8 月 10 日
I have a cell matrix with size 1165x1 cell. In each cell there is one value i.e. number 31 that needs to be found and made NaN.
For example:
A = {[1,2],[3,4],[5 31], [31,6]};
I would like to make 31 = NaN where ever it is seen. Just like matrix B:
B = {[1,2],[3,4],[5 NaN], [NaN,6]};
Any help is greatly appriciated.

採用された回答

Jan
Jan 2022 年 8 月 9 日
編集済み: Jan 2022 年 8 月 9 日
Start with a simple loop:
A = {[1,2], [3,4], [5 31], [31,6]};
B = A;
for k = 1:numel(B)
b = B{k};
m = (b == 31);
if any(m)
b(m) = NaN;
B{k} = b;
end
end
This can be condensed into a cellfun method:
p = [1, NaN];
B = cellfun(@(a) a .* p((a == 31) + 1), A, 'UniformOutput', 0)
B = 1×4 cell array
{[1 2]} {[3 4]} {[5 NaN]} {[NaN 6]}

その他の回答 (2 件)

Manas Shivakumar
Manas Shivakumar 2022 年 8 月 9 日
There are several ways to do this.
1) convert to matrix, replace and convert back to cell array:
tmp = cell2mat(A);
tmp(tmp == 31) == Nan;
A = num2cell(tmp)
2) use cellfun:
A(cellfun(@(elem) elem == 31, A)) = {Nan}
  3 件のコメント
Image Analyst
Image Analyst 2022 年 8 月 9 日
Correct Nan to Nan or nan. But still not right. Just to illustrate:
% Method 1
A = {[1,2],[3,4],[5 31], [31,6]}
A = 1×4 cell array
{[1 2]} {[3 4]} {[5 31]} {[31 6]}
tmp = cell2mat(A);
tmp(tmp == 31) == NaN;
A = num2cell(tmp)
A = 1×8 cell array
{[1]} {[2]} {[3]} {[4]} {[5]} {[31]} {[31]} {[6]}
% Method 2:
A = {[1,2],[3,4],[5 31], [31,6]};
A(cellfun(@(elem) elem == 31, A)) = {NaN}
Error using cellfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
@Manas Shivakumar Can you try again?
dpb
dpb 2022 年 8 月 9 日
The num2cell conversion also destroys the original cell sizes by placing every element into its own cell. One would have to write something like
mat2cell(cell2mat(A),[1],[2 2 2 2])
ans =
1×4 cell array
{1×2 double} {1×2 double} {1×2 double} {1×2 double}
>>
to get the original back.

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


MP
MP 2022 年 8 月 10 日
Thank you so much to everyone for their valuable time and efforts.
It saved a lot time of mine!

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by