How can I define a a column of 180 rows as variable "x" in order to use the fmincon function?
1 view (last 30 days)
Show older comments
Dear all,
First of all, I'd like to say that I'm not experienced in working with Matlab, and please excuse me if I make mistakes.
I have to maximize an objective function using fmincon, as my obj. fun. is a linear programming problem with linear constraints "Aeq" and a non-linear constraint "nonlcon". Basically, my objective function is a sumproduct function : f=sum(a(1:180).*x(1:180)), where a(1:180) are my parameters (known). What I don't know how to do, is to define the X (my 1 column and 180 rows matrix containing 180 variables). Kindly think of X as X(1), X(2) to X(180).
Thank you a lot in advance!
Kind regards, Alex
0 Comments
Accepted Answer
John D'Errico
on 24 May 2015
Edited: John D'Errico
on 24 May 2015
I suppose if you have nonlinear constraints, fmincon is the solution.
As for how to have that as a function, trivial.
f = @(x) sum(a.*x);
Or, with one less character...
f = @(x) dot(a,x);
Or with even fewer characters...
f = @(x) a'*x;
3 Comments
John D'Errico
on 24 May 2015
I think you don't know how to write a function so that it returns an argument.
As it is, I showed you how to write that function in a way that did not even need an m-file at all. Anyway, I think you need to start reading basic tutorials. For example, the line
size(a);
in your code does nothing at all. It has no purpose.
If you INSIST on the use of an m-file, do it like this:
function f = myfun(x)
a =[0.684487949143737;1.18483594161165;0.695412371288530;-0.106350487];
f = sum(a.*x);
You need to see and understand the difference.
More Answers (1)
Walter Roberson
on 24 May 2015
fmincon passes in x as a column vector to the function. If you define "a" as being a row vector then you can get rid of the explicit sum by using matrix multiplication,
f = a' * x;
where a has been created as a column vector.
It is better to create your "a" outside the function and to parameterize your objective function. Before the fmincon call,
a = [0.684487949143737;1.18483594161165;0.695412371288530;.....-0.106350487000000;];
Then the call itself would be
fmincon(@(x) a' * x, ....)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!