Function to find solutions to Ax=b

조회 수: 7 (최근 30일)
Isac Eriksson
Isac Eriksson 2019년 2월 13일
댓글: Isac Eriksson 2019년 2월 13일
I'm trying to code a function that will solve the linear system of equations Ax=b for a matrix A that is m by n.
The approche is to basicly make your own rref() to find the solution to Ax=b, however the way I've done it only allows for a correct solution shen A is m by m.
So, my question is how do I go about to have the function work A is m by n?
I get the error:
Index in position 1 exceeds array bounds (must not exceed 3).
Error in mygauss (line 15)
augA(col_i,:) = augA(col_i,:) - augA(row_i,:)*augA(col_i,row_i);
The "must not exceed #" is depending on dimension m of A.
function x = mygauss(A,b)
%--------- OUTPUT ----------
% x : the solution to Ax=b
%--------- INPUT -----------
% A : a m by n matrix
% b : a m by 1 vector
%---------------------------
augA = [A b];
[m,n] = size(A);
for row_i = 1:m
augA(row_i,:) = augA(row_i,:)/augA(row_i,row_i);
for col_i = 1:n
if row_i ~= col_i
augA(col_i,:) = augA(col_i,:) - augA(row_i,:)*augA(col_i,row_i);
end
end
end
x = augA(:,n+1);
end

답변 (1개)

aara
aara 2019년 2월 13일
You must consider when the matrix A has more columns than elements (n>m). From lines 12 to 15 (shown below) would use col_i for a row index and cause you the error:
for col_i = 1:n
if row_i ~= col_i
augA(col_i,:) = augA(col_i,:) - augA(row_i,:)*augA(col_i,row_i);
%in the line above, if number of columns is more than number of rows in matrix A you would
%exceed row dimensions of A.
end
I hope this helps
  댓글 수: 1
Isac Eriksson
Isac Eriksson 2019년 2월 13일
Thanks! that gave me some needed insight. The issue seems to be with line 13
for col_i = 1:n
The avriable col_i (column index) through me off. I thought sence it was the column n I was working with that col_i would need to go from 1 to the number of columns n. col_i is in fact just the indicator of the column position. Therfore the correct line of code is;
for col_i = 1:m

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by