What does the expression x(ind -1) mean?

7 vues (au cours des 30 derniers jours)
Ryan
Ryan le 17 Nov 2015
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 commentaires
Guillaume
Guillaume le 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
Ryan le 17 Nov 2015
I completely agree! That is exactly what they were doing, and it is confusing. I had a dumb moment and for whatever reason thought (ind -1) was somehow different from (ind - 1) or (ind-1).
Thanks!

Connectez-vous pour commenter.

Réponse acceptée

the cyclist
the cyclist le 17 Nov 2015
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).

Plus de réponses (1)

Stephen23
Stephen23 le 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.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by