Function to find solutions to Ax=b

2 views (last 30 days)
Isac Eriksson
Isac Eriksson on 13 Feb 2019
Commented: Isac Eriksson on 13 Feb 2019
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

Answers (1)

aara
aara on 13 Feb 2019
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 Comment
Isac Eriksson
Isac Eriksson on 13 Feb 2019
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

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!