Guassian Function, for loop only runs once???

a=[A,B];
for i=1:4;
a(2,i)=a(2,i)-(a(2,1)/a(1,1)).*a(1,i)
end
This is one of my first lines in my function but I do not know what this for loop only runs once A is a 3X3 matrix and B is a 3X1 which I combined for an augmented matrix

2 Comments

The four-loop definitely runs 4 times.
As evidence, insert this line anywhere inside your for-loop and the iteration number will be displayed in the command window.
fprintf('iteration #%d\n', i)
Only the 2nd row of 'a' will be affected by your code. Perhaps that's causing unexpected results?
Thank you, it is running four times but after the first iteration it doesn't change values. I am working row by row, so I was waiting to ensure my second row worked before moving onto the third.
A=[1 2 3; 3 2 1; 1 2 2];
B=[3; 4; 5];
I have been using these numbers as practice values since I worked it out by hand previously, and the second row should change to 0 -4 -8 -5
But the code I had only changes the second row to 0 2 1 4

Sign in to comment.

 Accepted Answer

Adam Danz
Adam Danz on 4 Feb 2019
Edited: Adam Danz on 4 Feb 2019
You're probably indexing incorrectly and instead of using the variable 'i', you're accidentally using a hard-coded value (maybe 1, by accident?)
Here's why your values aren't changing.
On the first iteration, you are replacing the value a(2,1) with a zero (see below)
i = 1
a(2,i) = a(2,i)-(a(2,1)/a(1,1)).*a(1,i)
% |______________________| this section is merely (Q/R) * R which just equals Q on the first iteration
% that reduces to
a(2,i) = a(2,i) - a(2,i) % which equals 0
On all following iterations, you're using that zero in the numerator of a fraction which will always equal 0 (see below)
i = 1 %, 3, 4
a(2,i) = a(2,i)-(a(2,1)/a(1,1)).*a(1,i)
% ( 0 /a(1,1)).*a(1,i) and that will always equal 0
% so = a(2,i) - 0 that will never change the value of a(2,i)
All of this results in only 1 change and that change happens on the first iteration in position a(2,1).

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!