What is the difference between v(i):v(j) and v(i:j)?
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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.
.
更多回答(1 个)
Steven Lord
2021-10-28
编辑:Steven Lord
2021-10-28
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)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!