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

조회 수: 7 (최근 30일)
Ryan
Ryan 2015년 11월 17일
답변: Stephen23 2015년 11월 17일
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
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.
Ryan
Ryan 2015년 11월 17일
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!

댓글을 달려면 로그인하십시오.

채택된 답변

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

추가 답변 (1개)

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by