Matlab Function: Solving Ax=B using Gaussian Elimination where b is a n x m matrix not necessarily a n x 1 matrix.

30 Ansichten (letzte 30 Tage)
So I was given the pseudocode to solve Ax=b when b is a n x 1 matrix (and thus x also is). I was able to successfully write a function that accomplished that. Now, I'm struggling to alter my function to solve Ax=b where b can now be a n x m matrix (A must be a n x n matrix, and x is an n x m matrix as result of b being a n x m matrix). I feel like the code must be pretty similar to consider this more general case but I can't seem to figure it out for some reason. Here's the code that I have:
function x = gaussianelim(A,b);
[row,col]=size(A);
n = row;
x = zeros(n,1);
for k=1:n-1
for i=k+1:n
xMultiplier = A(i,k)/A(k,k);
for j=k+1:n
A(i,j) = A(i,j)-xMultiplier*A(k,j);
end
b(i) = b(i)-xMultiplier*b(k);
end
% backsubstitution:
x(n) = b(n)/A(n,n);
for i=n-1:-1:1
summation = b(i);
for j=i+1:n
summation = summation-A(i,j)*x(j);
end
x(i) = summation/A(i,i);
end
end
My code only works where b=nx1 matrix (and hence x is an nx1 matrix) but I need it to work when b is just an arbitrary n x m matrix. I would appreciate any help. Thank you.

Antworten (1)

Jan
Jan am 11 Jun. 2018
[row,col] = size(A);
n = row;
x = zeros(size(b));
for k = 1:n-1
for i = k+1:n
xMultiplier = A(i,k) / A(k,k);
for j=k+1:n
A(i,j) = A(i,j) - xMultiplier * A(k,j);
end
b(i, :) = b(i, :) - xMultiplier * b(k, :);
end
% There is a missing "end" ?!
% backsubstitution:
x(n, :) = b(n, :) / A(n,n);
for i = n-1:-1:1
summation = b(i, :);
for j = i+1:n
summation = summation - A(i,j) * x(j, :);
end
x(i, :) = summation / A(i,i);
end
Simply replace x(i) by x(i, :) and the same for b.
  1 Kommentar
Li Guobin
Li Guobin am 23 Feb. 2020
Hi
i encountered the same problem as Huskie. I tried the suggestion to replace X(i,j) by X(i,:) and it worked!
My question is why would the inner loop logic not work for "j"? Why is there a need to replace it with ":"?

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Linear Algebra finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by