2

I have a 6x3 array of functions, dens, in Matlab, in which each function has a two-dimensional vector z as input. I need to evaluate these functions at z=[2 3], all at the same time; I have tried

ev_dens = @(z) cellfun(@(myfun) myfun(z),dens,'UniformOutput',false);
z =[2 3];
ev_dens(z)

but I got this error

??? Index exceeds matrix dimensions.
Error in ==> @(myfun)myfun(z)
Error in ==> @(z)cellfun(@(myfun)myfun(z),dens,'UniformOutput',false)

Could you help me?

1
  • 1
    I am unable to reproduce the problem, what is dens? Using some dummy data (dens(1:6,1:3)={@(x)([x(2),x(1)+x(2)])}) I don't get any error. Commented May 6, 2014 at 11:24

1 Answer 1

2

Using the following example data:

f{1,1} = @(z)([z(1),z(1)])
f{1,2} = @(z)([z(1),z(2)])
f{2,1} = @(z)([z(2),z(1)])
f{2,2} = @(z)([z(2),z(2)])

z = [2,3];

Your method works fine:

cellfun(@(F)F(z), f,'UniformOutput',false)

So it sounds like perhaps you have an error in one of your functions in dens. Try a nested for loop and see where you error:

for ii = 1:size(dens,1)
    for jj = 1:size(dens,2)
        dens{ii,jj}(z)
    end
end

and then check the values of ii and jj after you get your error, the function at dens{ii,jj} has an error in it.


In order to correct for the issue you mention in the comments (i.e. some of your cell elements are empty (i.e. []), run this function first to convert your empty cells into function that output empty cells:

dens(cellfun(@isempty,dens)) = {@(z)([])}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help; I have finally discovered the problem in my code: inside the array of functions I have some cells=[]. The problem is that I cannot predict where the [] cells will be and I cannot delete them. Do you know a way to overcome this issue? I would like to get 0 or [] in arrayfun in correspondence to these cells.
how about calling this first dens(cellfun(@isempty,dens)) = {@(z)([])}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.