It is correct to call the function as the_function(A)
, but you have to make sure the function can handle a vector input. As you say, (the_val - 5)^2
tries to square the matrix (and it thus gives an error if the_val
is not square). To compute an element-wise power you use .^
instead of ^
.
So: in the definition of your function, you need to change
result = (the_val-5)^2;
to
result = (the_val-5).^2;
As an additional note, since your code as it stands does work with scalar inputs, you could also use the arrayfun
approach. The correct syntax would be (remove the @
):
arrayfun(the_function, A)
However, using arrayfun
is usually slower than defining your function such that it works directly with vector inputs (or "vectorizing" it). So, whenever possible, vectorize your function. That's what my .^
suggestion above does.