How do you write a Matlab function that determines the case of the soluion to Ax = b.
Afficher commentaires plus anciens
Write a MATLAB function called LeastSquares that determines the case of the solution to Ax = b. In addition, the function also solves for x accordingly and returns the norm of the error vector.
The function header should look like the following:
function [flag xstar cstar] = LeastSquares(A,b,method)
The inputs to this function are defined as follows:
A: a matrix of arbitrary size.
b: a column vector, which has the same number of rows as matrix A.
method: should be filled with either 'mldivide' or 'pseudoinverse'. The method that you specify will be used to solve for the cases where non-unique solutions exist. If method is not specified, the default method should be 'mldivide'.
The outputs for this function are as follows:
xstar: the solution to Ax = b.
cstar: the norm of the error vector.
flag is a string, with the following values, depending on the type of solution:
{ Unique Exact Solution: flag is '1-Unique Exact Solution'
{ Non-Unique Exact Solutions: flag is '2-Non-Unique Exact Solutions'
{ Unique Least Squares Solution: flag is '3-Unique Least Squares Solution'
{ Non-Unique Least Squares Solutions: flag is '4-Non-Unique Least Squares Solutions'
The test cases I have been given are as follows:
% Test Case
>> A = [1 2 3;2 4 8;3 5 7];
>> b = [22;54;53];
>> [flag xstar cstar] = LeastSquares(A,b)
flag =
1-Unique Exact Solution
xstar =
1.0000
3.0000
5.0000
cstar =
0
>> A = [1 5;2 10;3 15];
>> b = [10;20;30];
>> [flag xstar cstar] = LeastSquares(A,b,'mldivide')
flag =
2-Non-Unique Exact Solutions
xstar =
0
2.0000
cstar =
1.6281e-014
>> A = [1 2 3;2 4 6;3 6 9];
>> b = [22;54;77];
>> [flag xstar cstar] = LeastSquares(A,b,'pseudoinverse')
flag=
4-Non-Unique Least Squares Solutions
xstar =
1.8418
3.6837
5.5255
cstar =
4.5119
Any help would be greatly appreciated. Thank you.
1 commentaire
Walter Roberson
le 18 Oct 2012
Please ask a specific question, as otherwise we will just refer you to the documentation on how to program in MATLAB.
Réponses (1)
Hints:
- Use rank(A) to determine whether a solution is unique.
- Use rank([A,b]) to determine whether it is exact.
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!