workaround for handling a large number of variables in the objective function of lsqnonlin
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Abdelwahab Afifi
am 12 Mai 2020
Kommentiert: Abdelwahab Afifi
am 12 Mai 2020
I want to optimize my objective function
w0=zeros(m,1)
[w,resnorm] = lsqnonlin(@myfun,w0)
How can I dynamically define weights w(1) w(2) w(3) in my function to adapt any possible change in number of variables (m) as follow
function F = myfun(w)
global X % regression matrix of (nxm)
global Y % output vector (nx1)
F = Y - ( w(1)*X(:,1) + w(2)*X(:,2) + w(3)*X(:,3) + .. + w(m)*X(:,m) );
end
1 Kommentar
Stephen23
am 12 Mai 2020
Note that the global variables should be replaced by function parameterization:
Akzeptierte Antwort
Stephen23
am 12 Mai 2020
Bearbeitet: Stephen23
am 12 Mai 2020
>> X = rand(7,3);
>> w = rand(3,1);
>> w(1)*X(:,1) + w(2)*X(:,2) + w(3)*X(:,3) % what you do now
ans =
0.63892
0.43089
0.59637
0.89806
1.08999
0.98472
0.38443
>> X*w(:) % what you should do: matrix multiply
ans =
0.63892
0.43089
0.59637
0.89806
1.08999
0.98472
0.38443
3 Kommentare
Stephen23
am 12 Mai 2020
Bearbeitet: Stephen23
am 12 Mai 2020
"I ask about defining the objective function (myfun) interms of large number of variables (w)"
And that is what I gave you. Matrix multiplcation neatly solves your problem of how to "...dynamically define weights w(1) w(2) w(3) in my function to adapt any possible change in number of variables (m)". You gave this verbose code
w(1)*X(:,1) + w(2)*X(:,2) + w(3)*X(:,3) + .. + w(m)*X(:,m)
which I simply replaced with one matrix multply
X*w(:)
giving exactly the same output as your code, and yet it also works for any m (thus answering your question). So far you have not actually stated why it would not work, nor given any counter-example. If it did not work as expected please show your exact input data and the expected output.
function F = myfun(w)
global X % regression matrix of (nxm)
global Y % output vector (nx1)
F = Y - X*w(:);
end
Note that the global variables should be replaced by function parameterization:
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Problem-Based Optimization Setup finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!