필터 지우기
필터 지우기

How does Matlab interpret for loops when say I=n:-1:1

조회 수: 95 (최근 30일)
Ethan Boyce
Ethan Boyce 2020년 8월 31일
댓글: Luong Ngo 2021년 10월 13일
So this is a code for gaussian elimination, the code seems to work but my question is for clarification on the function of the for loop and how Matlab reads it. This is more a question for my own understanding of the computer language than the math involved.
the section of code I am looking at is
x=zeros(n,1);
for i=n:-1:1
x(i)=(A(i,end)-A(i,i+1:n)*x(i+1:n))/A(i,i);
end
So how would the algorithm read this. My intution says when it reads x(i+1:n), that the program will simply move to the next i in the loop.
  댓글 수: 2
KSSV
KSSV 2020년 8월 31일
i = n:-1:1
The above takes i values as n, n-1, n-2, .....3, 2,1.
Luong Ngo
Luong Ngo 2021년 10월 13일
@KSSV do you know loop 1:1:n mean?

댓글을 달려면 로그인하십시오.

채택된 답변

Steven Lord
Steven Lord 2020년 8월 31일
The only part of that code that changes the value of i is the for statement itself, and MATLAB automatically handles changing the value of i to the next element of the vector n:-1:1 when the control flow returns to the for statement.
The expression i+1:n reads the value of i and computes with that value but does not modify the value.
  댓글 수: 3
Steven Lord
Steven Lord 2020년 8월 31일
Almost.
x(i)=(A(i,end)-A(i,i+1:n)*x(i+1:n))/A(i,i);
Plugging in i = 4 and n = 4:
x(4)=(A(4,end)-A(4,4+1:4)*x(4+1:4))/A(4,4);
The expression 4+1:4 simplifies to the empty 1-by-0 vector since we perform addition (level 6 in the operator precedence table) before applying the colon operator (level 7.) How many steps does it take to get from 5 to 4 when you step forward by 1 unit each time? You can't get there from here.
Now if those i+1 terms were i-1 instead (subtraction is also at level 6) yes, those terms would be 3:4 and that creates a two element long vector. As long as x is a column vector that vector-vector multiplication would be defined and would return a scalar. The whole expression on the right side would then result in a scalar which fits nicely into the one element of x being reference on the left side.
Ethan Boyce
Ethan Boyce 2020년 9월 1일
Got it, thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by