Home > Back-end >  How to apply a relational operator on a cell in MATLAB?
How to apply a relational operator on a cell in MATLAB?

Time:09-21

I would like to know the number of values that are less than 0.0038 in a cell of 41 X 41 double.

For example, I have the cell below:

B = num2cell(rand(41));

When I applied such condition sum(A(:) < 0.0038), it gave me an error, which is Operator '<' is not supported for operands of type 'cell'.

So, do I need to convert the cell to a matrix and apply the operation? Or is there any specific way to use this condition on the cell directly?

CodePudding user response:

As you wrote, one way would be to convert B back to a numeric array. The other way, i.e. using the condition directly on the cell array, is possible with the cellfun function:

isSmaller = cellfun( @(X) X < 0.0038, B(:), 'UniformOutput', true )
numSmaller = sum(isSmaller)

Explanation:

  • cellfun applies the anonymous function @(X) X < 0.0038 on all cells of B.
  • It stores the results in the array isSmaller.
  • 'UniformOutput', true triggers that isSmaller is a numeric array. To store the results in a cell array you could use 'UniformOutput', false.

Remark: As beaker commented, in your example it is not necessary to convert randn(41) to a cell array in the first place. You could store it as a numeric array and apply the condition directly on the array. However, I assume that your example is meant as minimum working example (MWE).

  • Related