Anonymous function with summation of parameters
Mostrar comentarios más antiguos
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!
Respuestas (1)
Star Strider
el 22 de Sept. de 2016
Editada: Star Strider
el 22 de Sept. de 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 comentarios
Amor-Aniss Benmoussa
el 23 de Sept. de 2016
Star Strider
el 23 de Sept. de 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.
Categorías
Más información sobre Modeling en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!