Anonymous function with summation of parameters
Ältere Kommentare anzeigen
Hello,
I would like to create an anonymous function to minimize. The problem is that I have many variables that are in a matrix where each column represents a variable and lines the numbers of observations. I do not want to write the function as:
fun = @(b) (Y - b(1)*XX(:,1) - b(2)*XX(:,2) - b(3)*XX(:,3) - ... - b(N)*XX(:,N) );
Nobody knows how to include a type of summation because my attempts have not worked. I try this:
N = 100;
fun = @(b) (Y - symsum(b(t)*XX(:,t),t,1,N));
Thank you very much!
Antworten (1)
Star Strider
am 22 Sep. 2016
Bearbeitet: Star Strider
am 22 Sep. 2016
Unless I’m missing something, ‘fun’ involves straightforward matrix multiplication:
Y = randi(9, 10, 1); % Create Data
XX = randi([-9 9], 10, 5); % Create Data
fun = @(b) sum(Y - XX*b); % Function
B0 = rand(size(XX,2),1); % Initial Parameter Estimates
B = fminsearch(fun, B0); % Estimate Parameters
EDIT — Also consider:
B = XX\Y;
2 Kommentare
Amor-Aniss Benmoussa
am 23 Sep. 2016
Star Strider
am 23 Sep. 2016
My pleasure!
That will not give you the correct result.
This will:
fun = @(b) norm(Y - XX*b);
(This also corrects an error in my original code, where I used sum instead of norm.)
The most efficient code remains:
b = XX\Y;
This will also give you the correct result, (the same as using norm in ‘fun’), and much more efficiently.
Kategorien
Mehr zu Modeling finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!