Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply function on all matrix elements [closed]

Tags:

matrix

matlab

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?

like image 701
user1943029 Avatar asked Feb 18 '23 23:02

user1943029


1 Answers

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.

like image 184
Eitan T Avatar answered Feb 27 '23 15:02

Eitan T