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 Kommentare

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?
Abigail Osborne
Abigail Osborne am 4 Feb. 2019
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

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Adam Danz
Adam Danz am 4 Feb. 2019
Bearbeitet: Adam Danz am 4 Feb. 2019

0 Stimmen

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).

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by