In: Advanced Math
This is Using MATLAB:
I am trying to store the solution of this matrix because I want to do something with the result like find the norm of that answer however I am stuck and cannot seem to be able to. Help would be appreciated!
---------------------------------------------
MATLAB CODE:
close all
clear
clc
A = [1 -1 2 -1;
2 -2 2 -3;
1 1 1 0;
1 -1 4 5];
b = [-8 -20 -2 4]';
x = gauss_elim(A,b)
function x = gauss_elim(A, b)
[nrow, ~] = size(A);
nb = length(b);
x = zeros(1,nrow);
% Gaussian elimination
for i = 1:nrow-1
if A(i,i) == 0
t = min(find(A(i+1:nrow,i) ~= 0) + i);
if isempty(t)
disp ('Error: A matrix is singular');
return
end
temp = A(i,:); tb = b(i);
A(i,:) = A(t,:); b(i) = b(t);
A(t,:) = temp; b(t) = tb;
end
for j = i+1:nrow
m = -A(j,i) / A(i,i);
A(j,i) = 0;
A(j,i+1:nrow) = A(j,i+1:nrow) + m*A(i,i+1:nrow);
b(j) = b(j) + m*b(i);
end
end
% Back substitution
x(nrow) = b(nrow) / A(nrow,nrow);
fprintf('\n\nHas exact solution:\n')
for i = nrow-1:-1:1
x(i) = (b(i) - sum(x(i+1:nrow) .* A(i,i+1:nrow))) / A(i,i);
end
end
I think you want to say that for different system you will get
different solutions but you don't want to lose the previous
solution you want to store it.
you can simply write a=x at the end
your x vector will be saved as a
if you want to save series of vectors in a matrix for different n number of systems.
I am modifying your code it will ask to enter matrix A and vector b, n number of times and then it will save your n solutions column wise in a matrix.
clc;
clear all;
n=input('enter number of times you want to enter A and b
');
for k=1:n
A=input('enter your matrix ');
b=input('enter b vector ');
x = gauss_elim(A,b);
mat(:,k)=x
end
function x = gauss_elim(A, b)
[nrow, ~] = size(A);
nb = length(b);
x = zeros(1,nrow);
% Gaussian elimination
for i = 1:nrow-1
if A(i,i) == 0
t = min(find(A(i+1:nrow,i) ~= 0) + i);
if isempty(t)
disp ('Error: A matrix is singular');
return
end
temp = A(i,:); tb = b(i);
A(i,:) = A(t,:); b(i) = b(t);
A(t,:) = temp; b(t) = tb;
end
for j = i+1:nrow
m = -A(j,i) / A(i,i);
A(j,i) = 0;
A(j,i+1:nrow) = A(j,i+1:nrow) + m*A(i,i+1:nrow);
b(j) = b(j) + m*b(i);
end
end
% Back substitution
x(nrow) = b(nrow) / A(nrow,nrow);
fprintf('\n\nHas exact solution:\n')
for i = nrow-1:-1:1
x(i) = (b(i) - sum(x(i+1:nrow) .* A(i,i+1:nrow))) / A(i,i);
end
end