fminsearch with matrices help

8 views (last 30 days)
James Whitehouse
James Whitehouse on 19 Nov 2020
Edited: Bruno Luong on 19 Nov 2020
I'm attempting to use fminsearch to optimise the components of a matrix to fit some data.
The equation I am looking to fit to the data is:
(y - A*x)^2
where y and x are 150x3 matrices of data, and A is a 3x3 matrix where A(i,j) are the parameters I'm looking to optimise.
The code I have so far is:
type sseval
function sse = sseval(p,x,y)
A1 = p(1);
A2 = p(2);
A3 = p(3);
A4 = p(4);
A5 = p(5);
A6 = p(6);
A7 = p(7);
A8 = p(8);
A9 = p(9);
M = [A1 A2 A3; A4 A5 A6; A7 A8 A9];
sse = sum((y - M*x)^2);
end
And then seperately:
fun = @(p)sseval(p,x,y)
p0 = rand(9,1)
bestp = fminsearch(fun,p0)
When i try this the error i recieve is:
Error using @(p)sseval(p,x,y)
'sseval' is used in Curve Fitting via Optimization.
Error in fminsearch (line 200)
fv(:,1) = funfcn(x,varargin{:});

Answers (3)

Ameer Hamza
Ameer Hamza on 19 Nov 2020
Edited: Ameer Hamza on 19 Nov 2020
x and y should be 3x150 to match the dimensions of matrix A. Following shows the correct code with fminsearch
x = rand(3, 150);
y = rand(3, 150);
fun = @(p) sseval(p, x,y)
p0 = rand(9,1)
bestp = fminsearch(fun,p0)
function sse = sseval(p,x,y)
M = reshape(p, [3 3]);
sse = sum((y - M*x).^2, 'all');
end
But note that you don't need fminsearch for this. You can directly use mrdivide / operator
x = rand(3, 150);
y = rand(3, 150);
A = y/x
This will likely be much more efficient than fminsearch.

Star Strider
Star Strider on 19 Nov 2020
Edited: Star Strider on 19 Nov 2020
This might do what you want:
x = rand(150,3); % Create Data
y = rand(150,3); % Create Data
A = x \ y;
Note that ‘A’ is the (3x3) matrix that appears to be the desired result.

Bruno Luong
Bruno Luong on 19 Nov 2020
Edited: Bruno Luong on 19 Nov 2020
Sort out the dimensions of the matrix before doing anything on paper, programming, etc...
>> x=rand(150,3);
>> A=rand(3,3)
A =
0.3181 0.6456 0.5447
0.1192 0.4795 0.6473
0.9398 0.6393 0.5439
>> y=x*A; % A*x does not make sense
>> Areconstruct = x\y
Areconstruct =
0.3181 0.6456 0.5447
0.1192 0.4795 0.6473
0.9398 0.6393 0.5439

Community Treasure Hunt

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

Start Hunting!