Hello, Can you help me to resolve Ax=B by gauss elimination in matlab with
A =
-2.1000 -0.5000 -0.9000 -1.9000 1.2000 0.1000
0.6000 0 -1.9000 2.4000 -1.7000 0.2000
2.0000 -0.5000 0 -0.2000 0.4000 -0.5000
2.2000 0.1000 1.2000 0.4000 0.5000 0.7000
3.3800 0.6400 -3.4100 4.0800 -1.8900 1.4600
-0.2300 -0.1900 0.2300 2.6700 -2.7600 -1.1300
-0.6400 -0.1400 -1.0500 0.0200 -0.0200 0.2200
b =
-0.8000
-0.8000
0.7000
1.7000
1.4000
-2.3600
-0.4600
Here is what i have done , but i have an error : Index in position 2 exceeds array bounds (must not exceed 7).
function x = GAUSS_ELIM(A, b)
%% Create permutation vector
n = size(A, 1); % Size of input matrix
r = zeros(n, 1); % Initialize permutation vector
for i = 1 : 1 : n
r(i) = i;
end
%% Apply Gaussian elimination and rearrange permutation vector
x = zeros(n, 1); % Initialize solution vector
for k = 1 : 1 : n % Go through each element in permutation vector
% Compare each element in r(k)th column for the max
max = abs(A(r(k), r(k)));
max_pos = k;
for l = k : 1 : n
if abs(A(r(l), r(k))) > max
max = abs(A(r(l), r(k)));
max_pos = l;
end
end
% Switch the kth r-vector element with max r-vector element
temp_r = r;
r(k) = temp_r(max_pos);
r(max_pos) = temp_r(k);
% Eliminate A-vector elements in r(k)th column below r(k)th row
for i = 1 : 1 : n
if i ~= k
zeta = A(r(i), k) / A(r(k), k);
for j = k : 1 : n
A(r(i), j) = A(r(i), j) - A(r(k), j) * zeta;
end
b(r(i)) = b(r(i)) - b(r(k)) * zeta;
end
end
end
% Compute the solution frpm the diagonalized A-matrix
for i = 1 : 1 : n
x(i) = b(r(i)) / A(r(i), i);
end
end

4 commentaires

dpb
dpb le 19 Jan 2020
  1. Indent your code so it can be read more easily
  2. first loop isn't needed--replace
r = zeros(n, 1); % Initialize permutation vector
for i = 1 : 1 : n
r(i) = i;
end
with
r=[1:n].'; % initialize permutation vector
Isn't your problem, but may as well use MATLAB syntax, it is after all, "MATrix LABoratory".
3. You didn't tell where the error occurs, even.
Wow I didn't see that we could write the code this way ! It's much better thanks !
And yes sorry, the error is :
Index in position 2 exceeds array bounds (must not exceed 7).
Error in gauss (line 65)
A(j,k) = A(j,k) - m*A(i,k);
dpb
dpb le 19 Jan 2020
OK, so k is outside bounds of A.
BUT, that error is for a function gauss while your function above is named |GAUSS_ELIM| and the above code line doesn't exist in that function.
You're debugging/executing different function than you think you are, apparently.
yes sorry again , it's because Im working with 2 differents function , here is the error :
Index in position 2 exceeds array bounds (must not exceed 6).
Error in GAUSS_ELIM (line 57)
A(r(i), j) = A(r(i), j) - A(r(k), j) * zeta;

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Linear Algebra dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by