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

4 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Star Strider
Star Strider il 28 Ott 2021
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 Commenti
SelDen
SelDen il 28 Ott 2021
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.

Accedi per commentare.

Più risposte (1)

Steven Lord
Steven Lord il 28 Ott 2021
Modificato: Steven Lord il 28 Ott 2021
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 Commento
SelDen
SelDen il 28 Ott 2021
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.

Accedi per commentare.

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by