Problem in MATLAB Code for solving desired 'n' number of simultaneous equations of the type Ax = b provided that the solving involves the method of upper triangular matrix and the values of A and b are evolved into Aprime and bprime along with the x values.
The problem is to write a code that can solve "n" number of simultaneous equation of the type Ax = b using upper triangulation matrix. The values of A and b are given as matrix in the command window. The code should return Aprime, bprime and x values as the answer when the program is run successfully. The code should also give the output as "Error, Matrix dimensions doesn't match" (or whatever !) for certain equations ! The code works fine except it shows an error along with the above given Error message.
The code I used is as follows,
function [x, Aprime, bprime]=solved(A,b)
n = size(A);
% Assign the size of A to n.
if (n(1)~= n(2)) || (det(A) == 0)
% Checking through the determinant method for dimension error.
disp('ERROR!! Matrix dimensions should agree.')
else
for j=1 %:n-1
% Fix the first value of j to 1.
if A(j,j)==0
u=A(j,:);
A(j,:)=A(j+1,:);
A(j+1,:)=u;
%using u as a temperary value "u", to save the row,to swap the positions of two rows.
v=b(j);
b(j)=b(j+1);
b(j+1)=v;
%using u as a temperary variable "v", to save the row,to interchange the positions of two rows in b matrix.
end
for i=j+1:n
if A(i,j)~=0
%If the first number of the particular row be zero.
b(i)=b(j)+(b(i)*(-A(j,j)/A(i,j)));
A(i,:) = A(j,:)+(A(i,:)*(-A(j,j)/A(i,j)));
end
%After this 'for'loop, the matrix becomes a upper triangle matrix.
end
Aprime=A;
bprime=b;
x=A\b;
% Using this command the values of x,y,z can be found.
end
end
end
Please provide the suitable correction....
Results as obtained on the command window,
A = [1 1 0;2 1 1;1 2 3]
A =
1 1 0
2 1 1
1 2 3
b= [3;7;14]
b =
3
7
14
[x, Aprime, bprime] = solved(A, b)
x =
1
2
3
Aprime =
1.0000 1.0000 0
0 0.5000 -0.5000
0 -1.0000 -3.0000
bprime =
3.0000
-0.5000 -11.0000
The second type is,
A = [1 2 3; 4 5 6]
A =
1 2 3
4 5 6
b = [7;8;9;10]
b =
7
8
9
10
[x, Aprime, bprime] = solved(A, b) ERROR!! Matrix dimensions should agree. Error in solved (line 2) n = size(A); Output argument "x" (and maybe others) not assigned during call to "C:\Users\Hari\Documents\solved.m>solved".
Instead of using disp
, use the function error
to communicate an error. That will tell MATLAB not to try to continue with execution after the error. Plus, the style will match builtin MATLAB errors.