|
Hi Subrat,
If you only have a few optimization problems defined in Excel, I agree with
Bruno that you should retype the objectives and constraints in MATLAB as he
suggests.
However, if you have many existing problems defined in Excel you may want an
automated route. One way to do this is as follows:
- Import the excel file as you have done already
- Use the symbolic math toolbox to create function handles from the imported
strings
- Pass these functions to fmincon
Note that you need the latest release of MATLAB (R2008b) and the Symbolic
Math Toolbox to do this.
A simple example of this approach is shown below:
function x = optimSym
% Simulate read from excel file
textread{1, 1} = 'sin(x)';
textread{1, 2} = 'x^2 - 1';
textread{1, 3} = '-tan(x) -1';
nCon = size(textread, 2) - 1;
% Convert the strings to matlab functions via symbolic toolbox
f = matlabFunction(sym(textread{1, 1}));
fCon = cell(1, nCon);
fCon{1} = matlabFunction(sym(textread{1, 2}));
fCon{2} = matlabFunction(sym(textread{1, 3}));
% Call fmincon
opts = optimset('fmincon');
opts = optimset(opts, 'Algorithm', 'active-set');
x = fmincon(f, 0.5, [], [], [], [], -pi, pi, @(x)evalCon(x, fCon), opts);
function [c, ceq] = evalCon(x, fCon)
nCon = length(fCon);
c = zeros(nCon, 1);
for i = 1:nCon
c(i) = fCon{i}(x);
end
ceq = [];
Hope this helps.
Best regards,
Paul
"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message
news:gd0ff2$isb$1@fred.mathworks.com...
> "Subrat Swain" <swain.subrat01@gmail.com> wrote in message
> <gd0ct3$ptb$1@fred.mathworks.com>...
>
>> OBJECTIVE Function .M file
>> function f = objfun(x)
>> f = @(textdata)textdata{1,6};
>> // textdata is the imported excel file containing equation for objective
>> function.
>
> You cannot do that. Under Matlab textdata{1,6} is interpreted as a
> *string* (char array) and not a command or function. You have to enter the
> equation.
>
> Example: if textdata{1,6} is '3*x + 5'
>
> then you have to type
>
> f = @(x) (3*x + 5);
>
> Same for the constraints.
>
> Bruno
>
> PS: there is an "eval" function that can accomplish the conversion from
> string to function, but you are better to stay away from it for now.
>
|