What is the difference between v(i):v(j) and v(i:j)?
2 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Star Strider
on 28 Oct 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.
.
More Answers (1)
Steven Lord
on 28 Oct 2021
Edited: Steven Lord
on 28 Oct 2021
v = (1:10).^2
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]
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)
Now imagine that v was not in ascending order.
v2 = flip(v)
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)
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)
See Also
Categories
Find more on Structures 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!