Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a function into a matlab function

Tags:

vector

matlab

I'm trying build a matlab function that will evaluate a function and vector that are sent in as parameters. I'm having a hard time trying to figure out how to send in the function so that it can be evaluated in the matlab function. I figured out how to do it without the function but I'm a little lost trying to evaluate it within a matlab function. Below is my code...

This is what I'm trying to do...

x = [x1 x2]';
f = x(x1)^2 + 2 * (x2)^2

x = [5 10];
f = (5)^2 + 2 * (10)^2 % which I would like to return 225, not a column vector

This is what I have and what I have tried...

x = [5 10]';

% without using a matlab function
% k = 1
% f = x(k)^2 + 2 * x(k + 1)^2;   % returns the correct answer of 225

f = x^2 + 2 * x^2       % complains about the scalar 2
f = x.^2 + 2 * x.^2     % returns a column vector [75; 300]
function [value] = evalFunction(f,x)
value = f(x);

I've tried...

f = @(x) x.^2 + 2 * (x+1).^2;
value = evalFunction(@f,x)      %Error: "f" was previously used as a variable

So I tried...

f = @(x) x.^2 + 2 * (x+1).^2;
value = evalFunction(f,x)       %value = [97;342]

I'm new to matlab so any help is appreciated. I've been doing some research and found some stuff here on stackoverflow but can't seem to get it to work. I've seen there are other ways to do this, but I will eventually be adding more code to the matlab evalFunction function so I'd like to do it this way. Thanks!

like image 714
user2743 Avatar asked Nov 24 '25 05:11

user2743


2 Answers

Anonymous functions and function handles plus array indexing. Taking x as a 2-element vector, define and use your function like:

f = @(x) x(1).^2 + 2 * x(2).^2;
value = evalFunction(f,x) % but you can just do f(x) if that is all you need

However, if evalFunction does nothing other than evaluate f at x, then you don't need it at all. Just do f(x).

Alternately,

f = @(x1,x2) x1.^2 + 2*x2.^2;
value = evalFunction(f,x1,x2); % here your function will call it by f(x1,x2)
like image 197
chappjc Avatar answered Nov 27 '25 01:11

chappjc


You are probably coming at this from a C background - in Matlab, x+1 is the entire vector x with 1 added - not the element offset by 1.

The function you need is

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

or, to be a little more "matlab-like":

f = @(x) [1 2] * x(1:2)'.^2;

Which performs the element-wise square of the first two elements of x as a column vector, and then does the matrix multiplication with [1 2], resulting in

1 * x(1) .^2 + 2 * x(2) .^2;

Which seems to be what you were asking for.

caveat: did not have opportunity to test this...

like image 20
Floris Avatar answered Nov 27 '25 00:11

Floris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!