Anonymous function with summation of parameters
이전 댓글 표시
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!
답변 (1개)
Star Strider
2016년 9월 22일
편집: Star Strider
2016년 9월 22일
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
Amor-Aniss Benmoussa
2016년 9월 23일
Star Strider
2016년 9월 23일
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.
카테고리
도움말 센터 및 File Exchange에서 Modeling에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!