Function to find solutions to Ax=b
조회 수: 7 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!