What does the expression x(ind -1) mean?
Show older comments
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 Comments
Guillaume
on 17 Nov 2015
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.
Ryan
on 17 Nov 2015
Accepted Answer
More Answers (1)
Stephen23
on 17 Nov 2015
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.
Categories
Find more on Construction 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!