Solving a least squares problem using QR decomposition
9 views (last 30 days)
Show older comments
"Given the least squares problem ||b - Ax||_2 = min_{y in R^n} ||b - Ax||_2 where A in R^{mxn} and b in R^m are given, and A is full-rank.
Write a MATLAB algorithm that solves the problem using the Matlab’s built-in QR Decomposition (qr) assuming m => n. "
Here's my code, but whenever I run it, I get an error in line 3: "Too many output arguments". What is the problem?
function[x] = ded(A,b)
[m,n] = size(A);
[Q, R, P] = qr(A);
c = Q'*b;
tol = max(size(A))*eps*abs(R(1,1));
r = 1;
while ( abs(R(r+1,r+1)) >= tol && r < n ); r = r+1; end
y1 = R(1:r,1:r) \ c(1:r);
y2 = zeros(n-r,1);
x = P*[y1;y2]
0 Comments
Answers (1)
Image Analyst
on 15 Nov 2020
How are you calling ded()? What are you passing in for A and b? And according to the error you're expecting more than one output, so you're calling it like
[x, x2, x3] = ded(A,b)
with 2 or more outputs when ded returns only one output. Try with only one output:
x = ded(A,b)
Also, in
function[x] = ded(A,b)
you must have a space after the function key word and before the left bracket.
2 Comments
Image Analyst
on 15 Nov 2020
Edited: Image Analyst
on 15 Nov 2020
OK, so that's how you're defining A and b, but what about my first, and most important question? Again:
"How are you calling ded()? "
You have not supplied us with your code, so we can't edit anything yet. I don't see anywhere in your posted code where you said you're calling it something like
[x, x2, x3] = ded(A,b)
Why not? Why won't you tell us how you're calling this function? Just to be super explicit, that will be on line 3 of your main script (not this function). Please attach the main script m-file, and the ded function m-file with the paper clip icon.
See Also
Categories
Find more on Time Series Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!