Search code examples
matlabfunctioncell

Converting a function to cellfun format in MATLAB


I had a matrix A(32x8) for which I wrote the following function

function x = y(A)
 x=[A(:,1:2),isnan(A(:,3:5)),A(:,6:end)];
 x(sum((x==1),2)>0,:) = [];
  end

Now I have an Array B (100x1) where each cell contains the Matrix A(32x8) with different values, So how can I write a function as same as above for all the cell in the array in MATLAB.

I tried following way

Class=cellfun(@(x) x{:,1:2},isnan{x{:,3:5}},x{:,6:end},B, 'UniformOutput', false);

Solution

  • To apply your function y o each element in the cell array B, use cellfun as follows:

    cellfun(@y, B, 'UniformOutput', false);
    

    @y is a handle to the function you wrote. It must exist, so that if you write y(B{1}) you get the correct output for the first element in B. cellfun simply applies that function to all elements in the cell array. It is equivalent to writing a loop over B.