What is the difference between v(i):v(j) and v(i:j)?

조회 수: 4 (최근 30일)
SelDen
SelDen 2021년 10월 28일
댓글: Star Strider 2021년 10월 28일
I was trying to refer the consective elements in an array within a loop. When I used v(i):v(j) MATLAB stopped giving an array output after sometime. The error got fixed when I used v(i:j). What is the reason of this?

채택된 답변

Star Strider
Star Strider 2021년 10월 28일
Without knowing what the elements of ‘v’ are, it is sifficult to say exactlly.
The ‘v(i):v(j)’ code creates a vector from ‘v(i)’ to ‘v(j)’ with a ‘step’ of 1. If the second is less than the first, no vector will be created. If the second is greater than the first while being less than 1 greater, it will return only the first value.
The ‘v(i:j)’ code creeates a vector of ‘v’ values between the ‘i’ and ‘j’ indices.
The two are entirely different, and will return entirely different results.
.
  댓글 수: 2
SelDen
SelDen 2021년 10월 28일
Thanks very much. I thought that the colon would be defined in v for some reason. In the code first elements of the array were already consecutive so the results were correct eventhough the code was wrong.
Star Strider
Star Strider 2021년 10월 28일
My pleasure!
.

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

추가 답변 (1개)

Steven Lord
Steven Lord 2021년 10월 28일
편집: Steven Lord 2021년 10월 28일
v = (1:10).^2
v = 1×10
1 4 9 16 25 36 49 64 81 100
If you ask for v(4:7) you're asking for the fourth, fifth, sixth, and seventh elements of v.
x1 = v(4:7) % [16 25 36 49]
x1 = 1×4
16 25 36 49
If you ask for v(4):v(7) you're asking for the vector 16:49 which is much longer.
x2 = v(4):v(7)
x2 = 1×34
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
Now imagine that v was not in ascending order.
v2 = flip(v)
v2 = 1×10
100 81 64 49 36 25 16 9 4 1
v2(4:7) is still the fourth through seventh elements of v2, which in this case is x1 flipped.
x3 = v2(4:7) % flip(x1)
x3 = 1×4
49 36 25 16
But v2(4):v2(7) is now 49:16. You can't get from 49 to 16 in steps of +1 so that result is empty.
x4 = v2(4):v2(7)
x4 = 1×0 empty double row vector
  댓글 수: 1
SelDen
SelDen 2021년 10월 28일
Thank you very much. It was very helpful. The array I was working with was [ 1 2 3 4 5 4 3 2 1]. It went downhill when v(i=4) = 4 and v(i=4)=4 and printed out an element as there was nothing between and after that since the numbers were in descending order the result became empty like you said.

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

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by