3
votes

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!

2
Note the difference between [1 2]^2 (which tries to do matrix multiplication on a row vector, and will throw an error) and [1 2].^2 which performs element-by-element multiplication - result is [1*1 2*2] or [1 4]. Besides that - "function handles" is indeed the thing you need to learn about. @chappj's answer contains links that should help. - Floris
Please see my updated question. Thanks for the help. - user2743
I updated the question to make more sense and not ask the proper question at the end :> - user2743

2 Answers

3
votes

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)
3
votes

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...