PROGRAMMING IN MATLAB Write a function with header [N, x] = myNumSols(A, b), whe
ID: 3679400 • Letter: P
Question
PROGRAMMING IN MATLAB
Write a function with header [N, x] = myNumSols(A, b), where A and b are a matrix and compatibly-sized column vector, respectively; N is the number of solutions of the system Ax = b; and x is a solution to the same system. If there are no solutions to the system of equations, then x should be an empty matrix. If there is one or an infinite number of solutions, then myNumSols should return one using linear algebra and systems of linear equations. You may assume that b is a column vector and that the number of elements in b is the same as the number of rows in A. The output x should be a column vector. You may assume that if the system has an infinite number of solutions, then the A matrix will have more columns than rows; that is, A is fat. In this case, you should solve the system using x = pinv(A) * b.
Test cases:
>> A = reshape(1:15, 3, 5);
>> b = [-5; -4; -3];
>> [N, x] = myNumSols(A, b)
N =
Inf
x =
1.0000
0.6000
0.2000
-0.2000
-0.6000
>> b = [-1.5; 2; 7];
>> [N, x] = myNumSols(A, b)
N =
0
x =
[ ]
>> A = 3 * eye(5);
>> b = [1; 2; 3; 4; 5];
>> [N, x] = myNumSols(A, b)
N =
1
x =
0.3333
0.6667
1.0000
1.3333
1.6667
Explanation / Answer
matalab function code:
function [N,x]=myNumSols(A,b)
[r,c]=size(A);
if r==c
x=inv(A)*b;
N=1;
else
for i=1:r
for j=1:c
B(i,j)=A(i,j);
end
B(i,j+1)=b(i,1);
end
Bref=rref(B);
count=0;
[r,c]=size(B);
for i=1:c
if(Bref(r,i)==0)
count=count+1;
end
end
if(count~=c)&&(Bref(r,c)~=0)
N=0;
x=[];
else
x=pinv(A)*b;
if isempty(x)
N=0;
else
N=Inf;
end
end
end
end
output at matlab coomand line:
>> A=reshape(1:15,3,5);
>> b=[-5;-4;-3];
>> [N,x]=myNumSols(A,b)
N =
Inf
x =
1.0000
0.6000
0.2000
-0.2000
-0.6000
>> b=[-1.5;2;7];
>> [N,x]=myNumSols(A,b)
N =
0
x =
[]
>> A=3*eye(5);
>> b=[1;2;3;4;5];
>> [N,x]=myNumSols(A,b)
N =
1
x =
0.3333
0.6667
1.0000
1.3333
1.6667
>>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.