user3185617
user3185617

Reputation: 65

How to pass the value of an array to a mathematical function in Matlab?

I have a defined mathematical function: f =Inline('x1^2+x2^2+2*x1*x2','x1','x2')

and I have an array that represents the number value of x1 and x2. (e.g. the array is A=[1 2])

I want to automate the process of getting the f(x1,x2), but I couldn't figure out the right way that Matlab can take in the array and assign values to x1 and x2.

What can I do to pass in the array values to the mathematical model and get the function value?

Upvotes: 0

Views: 90

Answers (1)

nalyd88
nalyd88

Reputation: 5128

You should be using anonymous functions instead of inline since inline will be removed in a future release of MATLAB.

Example (from the docs):

sqr = @(x) x.^2;
a = sqr(5)
a =
   25

In your case:

f = @(x) x(1)^2+x(2)^2+2*x(1)*x(2);

Now it expects x to be a two (or more) value array.

A = [1 2];
f(A) =
    9

Note:

I don't have MATLAB on my home computer so I haven't actually tested this but it should get you going in the right direction. Have a look over the docs and you'll be fine.

Upvotes: 2

Related Questions