Translate

MATLAB - Applying a function for each element in an array using arrayfun

I'm not a big matlab fan. For a project I needed to apply a function for each element in an array. For that arrayfun can be used.

Here is a simple example.

Say you have 3 arrays as follows.

A = [1,2,3,4]
B = [5,6,7,8]
C = [9,10,11,12]

And you need to calculate the value of a function myf, for A[i], B[i] and C[i] (i=1,2,3,4) which returns A[i] x B[i] + C[i]

You can do it as follows.

First define your function considering a single element.

function output=myf(a,b,c)
  output=a*b + c;
end

Then,

A = [1,2,3,4]
B = [5,6,7,8]
C = [9,10,11,12]

D = arrayfun(@myf,A,B,C)


Remember to have "@" before myf. It denotes a handle in matlab. If you forget it, matlab will try to evaluate the function instead of considering its handle, which may result in "Not enough input arguments" error.



2 comments:

  1. Very nice blog...
    Great information provided. We also provide Matlab Training in Noida. I appreciate your work.

    ReplyDelete
  2. I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in MATLAB, kindly contact us http://www.maxmunus.com/contact
    MaxMunus Offer World Class Virtual Instructor led training on MATLAB. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
    For Demo Contact us.
    Nitesh Kumar
    MaxMunus
    E-mail: nitesh@maxmunus.com
    Skype id: nitesh_maxmunus
    Ph:(+91) 8553912023
    http://www.maxmunus.com/




    ReplyDelete