Azzera filtri
Azzera filtri

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

7 visualizzazioni (ultimi 30 giorni)
Ryan
Ryan il 17 Nov 2015
Risposto: Stephen23 il 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 Commenti
Guillaume
Guillaume il 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 il 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!

Accedi per commentare.

Risposta accettata

the cyclist
the cyclist il 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).

Più risposte (1)

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

Community Treasure Hunt

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

Start Hunting!

Translated by