Applying Threshold to Matrix Within Cell Array

67 views Asked by At

I have a cell array called output. Each cell within output contains a 1024 x 1024 matrix. I would like to threshold each matrix so that elements below a given value are set to NaN.

I tried using:

output(output < 100000) = NaN; 

However, I feel that this is the wrong approach. Intuitively, I want to use a for loop, however, I don't think that will be the most efficient method possible.

Thoughts? Suggestions?

Thanks :)

1

There are 1 answers

1
Saeed Masoomi On

it can be done with cellfun function!cell fun can implement a function on every cell (it's like for loop) Assume below example

first consider you have a variable named a in cell form.

a{1,1} =
 1     2
 3     4

a{2,1} =
 1     2
 5     5

 a{1,2} =
 4     5
 1     2

 a{2,2} =
 5     5
 5     5

in this cell i want to substitute entries with NaN if entry lower than 3

So I write below function for this purpose

function out = main_func()
%% define a
a{1,1}=[1 2;3 4];
a{1,2}=[4 5;1 2];
a{2,1}=[1 2;5 5];
a{2,2}=[5 5;5 5];


out=cellfun(@(T) cell_f(T),a,'uniformOutput',false); % using cell fun function

function x = cell_f(x)
x(x<3)=nan; % if entries lower that 3 then substitute with Nan

the output will be like below

ans{1,1} =
 NaN   NaN
 3     4

ans{2,1} =
 NaN   NaN
 5     5

ans{1,2} =
 4     5
 NaN   NaN

ans{2,2} =
 5     5
 5     5