matlab数组下标可为正整数和逻辑数

百度知道中转载的:
选择数组中的数据有两种方法,一种是直接用下标选取,这是我们平时最常用的方法。比如a([1 3 4])。
另一种使用逻辑数组选取,很多人都不知道这种方法。
这种方法要求数组和逻辑数组的元素个数相等,比如a是数组,n是逻辑数组,则a(n)就是取a中与n为真的元素相对应的元素。比如a([1 0 1 1 0])就是取a的第1、3、4个元素,和a([1 3 4])等价。
这种方法对于删选数据非常有效,比如要选择a中大于5的元素,很多人都必须调用find函数,但其实直接用a(a>5)即可,运算速度也比调用find函数要快得多。
举个例子:
>>a=[3,2,1,4,5]
a =
     3     2     1     4     5
>> a([1,3,4])
ans =

     3     1     4

>> a([1 0 1 1 0])
Subscript indices must either be real positive integers or logicals. 
>> b=logical([1 0 1 1 0]) 
b =
     1     0     1     1     0
>> a(b)
ans =
     3     1     4

猜你喜欢

转载自blog.csdn.net/u011089523/article/details/80175289