How to make specific elements of a cell equal to zero?

Viewed 65

I have a 41 * 41 cell array, and I would like to make the values greater than 0.5 equal to zeros in Matlab, while keeping the rest of the values without any changes. Is it possible to work directly on the cell, or do we need to convert it to a matrix first?

My try

AAA = cell2mat( BBB );
for i = 1: length(AAA)
    for j = 1 : i
        if AAA(i,j) > 0.5
            AAA(i,i) = 0;
        else
            cc = AAA(i,j);
        end
    end
end
2 Answers

Here's one-liner to avoid converting the cell array to a matrix and then back to a cell array by calling cell2mat and num2cell/mat2cell.

Assuming an example cell array like this:

BBB = num2cell(rand(41));

Then use cellfun to apply a function to each cell:

CCC = cellfun(@(x)x.*(x<=0.5),BBB,'UniformOutput',false);

This will return a cell array, CCC, the same size as the input, BBB.

Since logical indexing is not supported for operands of type 'cell', you have to convert to matrix first. Use logical indexing on the matrix and convert back to cell. Assuming BBB is like BBB = num2cell(rand(41)), then

AAA = cell2mat(BBB);
AAA(AAA > 0.5) = 0;
BBB = num2cell(AAA)
Related