How to write a function that operates elementwise on a matrix?

396 Views Asked by At

I have written a function $f$ in Matlab that receives a number and returns a number, for example

function r = myFun(x)

r = (exp(x)+3)/2

end

I would now like that if $x$ was a matrix and not a scalar then the $f(x)$ would be defined and will return a matrix whos elements are the image of the elements of $x$ under $f$ (that is: the instead of an enter $a_{i,j}$ I want $f(a_{i,j})$

How can I achieve this ?

1

There are 1 best solutions below

0
On BEST ANSWER

MATLAB already does this for the exp() function. Try it out!

If you want other elementwise operations, just add a dot. That is:

  • Use x .* y instead of x * y.
  • Use x ./ y instead of x / y.
  • Use x .^ y instead of x ^ y.