Solving a least squares problem using QR decomposition

8 次查看(过去 30 天)
"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]

回答(1 个)

Image Analyst
Image Analyst 2020-11-15
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 个评论
Pascale Bou Chahine
Pascale Bou Chahine 2020-11-15
I'm taking A - rand(3,2), and b = rand(3,1)
I still don't know why I'm getting this error, can you edit my code to see where I went wrong please?
Image Analyst
Image Analyst 2020-11-15
编辑:Image Analyst 2020-11-15
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Time Series Objects 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by