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

Accepted Answer

John D'Errico
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
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.
Alex Stef
Alex Stef on 24 May 2015
Dear John, You are correct. I've followed your instructions and eventually I've found some results.
Thank you!

Sign in to comment.

More Answers (1)

Walter Roberson
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, ....)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!