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!