Anakin
Anakin

Reputation: 81

How to put vector into function's argument?

I would like to know how to put a vector into function's argument. Let the user enters a vector x=[x1 x2] and the coefficients a, b. And our task would be for example to plot a graph of a linear function a*x+b, where x=[x1 x2]. I thought that the beginning might look like this:

function L = linear([x1 x2], a, b) 
  .... 
  y = [x1 x2] * a + b 
  plot ([x1 x2], y) 

Unfortunately, it is all wrong. Matlab still reports ERROR. Help. Thanks

Upvotes: 1

Views: 237

Answers (1)

David K
David K

Reputation: 1346

Matlab does not allow you to specify two variables for a single input. There are two options here. First, you can assign x1 and x2 as separated arguments:

function L = linear(x1,x2,a,b)

Second, you can keep as a single input and index out your two variables:

function L = linear(x,a,b)
x1 = x(1);
x2 = x(2);

Another note - in the code you show, you only ever use [x1 x2] and never separate them out. You don't really even need to define x1 and x2 like I did in option 2 above. The confusion may be because you have them defined separately in your calling function. In that case you could call the function (not define) as you originally described: linear([x1 x2],a,b);

Upvotes: 1

Related Questions