Apply function on all matrix elements

11,571

Main problem

Undefined function or method 'an' for input arguments of type 'double'.

This means that MATLAB doesn't recognize your function an. Make sure that an is implemented in a separate m-file called an.m, and that it is located in your current working directory.

Additional problem

I can see that your arrayfun syntax is flawed. Once you solve your current problem, I predict that you will encounter another error message:

??? Error using ==> an
Too many input arguments.

The problem is that function an accepts only one input argument, but you're passing three arguments in arrayfun. Instead, either pass only one argument, for example:

arrayfun(@an, B);

or modify an to accept three arguments, for example:

function p = an(x, y, z)
    p = x + y + z

I'm not sure what you're trying to achieve, so it's up to you to choose.

Share:
11,571

Related videos on Youtube

user1943029
Author by

user1943029

Updated on June 04, 2022

Comments

  • user1943029
    user1943029 almost 2 years

    I want to apply a function on each element in a matrix. I've written the following code:

    function p = an(x)
        p= x + 1;
    end
    

    The matrix is for example:

    B = [1 2 3; 3 4 5; 6 7 8]
    

    When I try to do this:

    arrayfun(@an , B(1, :) , B(2, :), B(3, :))
    

    I get this error:

    ??? Error using ==> arrayfun
    Undefined function or method 'an' for input arguments of type 'double'.

    I can't understand why. How I can fix it? Is there a easier way to do it?

    • HebeleHododo
      HebeleHododo over 11 years
      What is your desired output?
  • user1943029
    user1943029 over 11 years
    Thank you very much! it works
  • user1943029
    user1943029 over 11 years
    I have one more question: if i will change the "an" function to: function ans = an(x) if x == 1 ans = x+1; else ans = x+2; end end How can I apply this function on each cell of the matrix? (I've tried to write: arrayfun(@an,B) but it doesn't work. thank you .
  • Eitan T
    Eitan T over 11 years
    @user1943029 you're using the variable ans which is already reserved keyword. Use another name and it should work.
  • user1943029
    user1943029 over 11 years
    It doesnt work with another name. Is there another way to solve it?
  • Eitan T
    Eitan T over 11 years
    Can you give more details about "it doesn't work"? Do you get an error message?