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!