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!

Answers (1)

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 Comments

Thanks a lot!
I found the answer with:
fun = @(b) Y - XX*b;
I thought that I had to define the different parameter b(1) to b(N) but this is not necessary.
Amor
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.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 21 Sep 2016

Commented:

on 23 Sep 2016

Community Treasure Hunt

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

Start Hunting!