0

I am trying to produce something like this in MATLAB with function handle

f=@(x,y)(x(1)*x(2)+y);

c=[2 3 4;5 9 2];

h=[5 1 2];

f(c,h)

The answer should be:

15    11    12

But when I write this code below, it just builds a number not an array.

f=@(x)(x(1)*x(2))

f(c)

answer:

10

Can someone explain me where I went wrong?

munk
  • 12,340
  • 8
  • 51
  • 71
  • What is it that you find wrong? What is your intended result? – Luis Mendo Mar 02 '14 at 16:52
  • 1
    Being pedantically literal, where you went wrong is in expecting 2*5 to be anything _other_ than 10. `x(1)` and `x(2)` are [linear indices](http://www.mathworks.co.uk/help/matlab/math/matrix-indexing.html#f1-85511) to single elements of the matrix. – Notlikethat Mar 02 '14 at 17:08

1 Answers1

0

I do not know what you expected here. The cause of the problem is quite clear.

a = 1;
b = 2;
c = [3 4];
d = a*b+c;

is a scalar + vector operation which always returns

ans = [a*b+c(1), a*b+c(2)];

however scalar*scalar which was the second case always returns a scalar. What you do is that you multiply the first matrix element of x (or c) with the second element. That is to say element c(1,1)*c(2,1) since matlab works columnwise. If you looks at your values you would probably notice the answer is incorrect as well, if you are trying to do what I think you are. You could try this instead,

f=@(x,y)(x(1,:).*x(2,:)+y);
c=[2 3 4;5 9 2];
h=[5 1 2];
f(c,h)

which multipies the elements on the first row of x with the same column on the second row and then adds y. An anonymous function takes a number of inputs and perform a defined operation, the same as ordinary functions or ordinary codes. You can see them as functions that does not require a call to another m file. The main differences (except that ordinary functions gives more freedom), are how they are handled by matlab and not in the syntax.

patrik
  • 4,506
  • 6
  • 24
  • 48