问题
Let's define, for example,
x = 10:10:2000;
As is well known, integer values can be used as indices:
>> x(9)
ans =
90
In Matlab, characters can often be used where a number would be expected, with Matlab doing the conversion automatically. For example, since the ASCII code of 'a'
is 97
,
>> 'a'+1
ans =
98
Can characters be also used as indices? Does Matlab convert them into integers?
回答1:
They can be used... but careful if the index is a single colon!
Let's define
>> x = 10:10:2000;
Indexing with 'a'
produces the 97-th element of x
, as expected:
>> x('a')
ans =
970
However, indexing with ':'
is a special case. The string ':'
acts as a :
index, thus producing a column vector of all values of x
. That is, x(':')
is the same as x(:)
:
>> x(':')
ans =
10
20
30
...
1990
2000
This means that the index ':'
is being evaluated (x(':')
acts like x(:)
), whereas other character arrays used as indices are not evaluated (x('a')
doesn't act like x(a)
):
>> a = 1;
>> x('a')
ans =
970
This also implies that with ':'
, converting to a numeric type before indexing does matter, unlike with other characters used as indices:
>> x(double('abc'))
ans =
970 980 990
>> x('abc')
ans =
970 980 990
>> x(double(':'))
ans =
580
>> x(':')
ans =
10
20
30
...
1990
2000
The "evaluated" behaviour of ':'
used as index was already known. What's surprising is the contrast with other characters or character arrays used as indices (which are not evaluated).
The examples have used a single dimension for simplicity, but the described behaviour also applies to multidimensional indexing. The same behaviour is observed in Octave too.
来源:https://stackoverflow.com/questions/36189651/can-characters-be-used-as-indices