MATLAB: How does the anonymous function work when one of the inputs is x

anonymous functionmatlab function

Hello all, I searched through the documentation for the anonymous function but I still didn't get anywhere with this!
a= 1; b = 2;
f1 =@(x, y) a*x + b*y;
a=2; b=1;
f2=@(x, y) a*x - b*y;
My question is: why does f1(1,x) return -1 1 3 and why does f2(x,1) return -3 -1 1
This is not a homework help question but rather a study help question, I am reviewing for my final and I am stuck on this. I do not understand how matlab gets to these numbers. Many thanks in advanced!

Best Answer

  • a= 1; b = 2;
    f1 =@(x, y) a*x + b*y;
    Remember that function call arguments are positional. That code means that when you invoke f1 passing in two arguments, then the value that is passed in the first position will be multipled by a, and the value that is passed in the second position will be multipled by b, and those two will be added.
    When you call
    then MATLAB will look in the workspace (and some other places if need be) to find the variable named x, and the value of x will be prepared and will pass in to the second parameter position, with the first parameter being 1. function f1 will receive those values by position, and in particular not by name. Within f1, whatever was passed in the first position is referred to as x for the duration of the function call, and what was passed in as the second argument will be referred to as y, no matter whether the values were passed in as literal numbers like the 1, or as variable names.
    Again: inside an anonymous function body, the variables named in the @() section are replaced by the values passed into the corresponding positions no matter what (if any) variable names are associated with those values.