Yue Huang
Yue Huang

Reputation: 11

Matlab: Can I access workspace variables in function definition?

I want to find constants a1, b1 which minimize

\sum_{k=1}^{n} |a_1 x_k + b_1 - y_k|

So I write following matlab code(nlp.m):

function NLP
x0 = ones(2, 1);
[a1b1, sum1] = fmincon(@objfun, x0, [], [], [], [], [], [], [])

function sum1 = objfun(a1b1)
sum1 = sum(abs(a1b1(1) * x + a1b1(2) - y));

with x and y n-vector created in workspace

However, when I run nlp.m I get the following error:

>> nlp
Undefined function or variable 'x'.
...

Seems that I can't get access to variables defined in workspace. So how can I deal with it?

Upvotes: 1

Views: 858

Answers (1)

Thierry Dalon
Thierry Dalon

Reputation: 926

You can access variables in the base workspace directly from a script but not a function. To pass these variables to your objective function see http://www.mathworks.com/help/optim/ug/passing-extra-parameters.html.

So you could change your function to using a script like this:

% NLP - script
x0 = ones(2, 1);
f = @(a1b1)objfun(a1b1,x,y);
[a1b1, sum1] = fmincon(@f, x0)

And define your objective function in a separate function:

function sum1 = objfun(a1b1, x, y)
sum1 = sum(abs(a1b1(1) * x + a1b1(2) - y));

An other alternative would be to save the base workspace to a file and load this file in your main function. In this case you could update your function like this:

function nlp
% save workspace variable to file
evalin('base','save(''ws.mat'',''x'',''y'');')
x0 = ones(2, 1);
s=load('ws.mat');
x=s.x;y=s.y;
f = @(a1b1)objfun(a1b1, x, y);
[a1b1, sum1] = fmincon(@f, x0);

function sum1 = objfun(a1b1, x, y)
sum1 = sum(abs(a1b1(1) * x + a1b1(2) - y));

Upvotes: 1

Related Questions