What does the expression x(ind -1) mean?
7 次查看(过去 30 天)
显示 更早的评论
I recently saw the following code and I'm curious as to what it is actually doing:
x(ind -1)
where "ind" is a vector of indices for x.
I played around with x = 1:10, ind = 2:2:10:
x(ind -1) = 2 4 6 8
x(ind -2) = 2 4 6 8
x(ind -3) = 2 4 6
x(ind -4) = 2 4 6
x(ind +1) = 2 4 6 8 10 12
I clearly see a pattern, but I can't explain in plain words what the expression x(ind -1) is really "saying." Can someone please explain?
Thanks!
--R
2 个评论
Guillaume
2015-11-17
I would recommend that you use different style for your expressions, such as
x(ind-1)
or
x(ind - 1)
This is important because [space minus number] usually means a negative number rather than a subtraction.
When I see your formatting, I wonder: "did the writer forget an operator between the ind and the negative number? Is there a bug?".
The less confusion you throw around, the easier the code is to debug and maintain.
采纳的回答
the cyclist
2015-11-17
This article about indexing arrays explains how it works.
By the way, it is not correct that
x(ind -2) == [2 4 6 8]
for x = 1:10 and ind = 2:2:10.
In fact, x(ind-2) will give an error, because it will try to access the 0th element of the vector, which does not exist (because MATLAB has 1-based indexing).
0 个评论
更多回答(1 个)
Stephen23
2015-11-17
You are getting confused because you are mixing indexing with vector generation and you are not looking at the intermediate results. Lets just look at the vector generation:
>> 2:2:10-1
ans =
2 4 6 8
>> 2:2:10-2
ans =
2 4 6 8
>> 2:2:10-3
ans =
2 4 6
>> 2:2:10-4
ans =
2 4 6
>> 2:2:10-5
ans =
2 4
You can see that the vector is created after the subtraction, so the last example is equivalent to this:
>> 2:2:5
ans =
2 4
You can read about the colon operator here:
and operator precedence here:
Note that the colon operator is listed with a lower priority than the subtraction operator.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!