字符可以用作索引吗? [英] Can characters be used as indices?

查看:212
本文介绍了字符可以用作索引吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,让我们定义

x = 10:10:2000;

众所周知,整数值可用作索引:

As is well known, integer values can be used as indices:

>> x(9)
ans =
    90

在Matlab中,通常可以在需要数字的地方使用字符,而Matlab会自动进行转换.例如,由于'a'的ASCII码是97

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

字符也可以用作索引吗? Matlab会将它们转换为整数吗?

Can characters be also used as indices? Does Matlab convert them into integers?

推荐答案

可以使用它们,但是要小心索引是否为单个冒号!

让我们定义

They can be used... but careful if the index is a single colon!

Let's define

>> x = 10:10:2000;

'a'编制索引会按预期产生x的第97个元素:

Indexing with 'a' produces the 97-th element of x, as expected:

>> x('a')
ans =
   970

但是,用 ':'建立索引是一种特殊情况.字符串':'用作:索引,从而产生所有x值的列向量.也就是说,x(':')x(:)相同:

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

这意味着正在对索引':'进行评估(x(':')的行为类似于x(:)),而用作索引的其他字符数组则不会进行评估( x('a')的行为不像x(a)):

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.

这篇关于字符可以用作索引吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆