我想知道以下最佳做法是什么:
我有两个矩阵, a1 (500 x 40)和a2 (1 x 500)。对于布尔型的a1 ,我想根据特定列中的值(即true或false)将数组分开。我还需要在a2分隔相应的条目。
我可以通过几个循环来做到这一点,或者甚至可以通过串联a1和a2进行逻辑测试,然后再次将它们分开,但是我想知道是否有一种常用的方法来处理这样的事情吗?
回答:
这是一个猜测,但这听起来像是要提取a2相应值的a1中每个列的真实条目。由于您说a1是布尔值(在MATLAB中称为
逻辑类型),因此可以通过以下方式使用
逻辑索引 :
vals1 = a2(a1(:,1)); %# Use column 1 of a1 as an index into a2 vals5 = a2(a1(:,5)); %# Use column 5 of a1 as an index into a2 ... 这是一个例子:
>> a1 = logical(randi([0 1],10,4)) %# Make a random logical matrix a1 = 0 0 1 1 0 1 0 0 1 1 1 1 1 0 1 0 0 0 1 1 0 0 1 0 0 1 1 0 1 0 0 0 1 1 0 1 1 0 0 0 >> a2 = 1:10; >> a2(a1(:,1)) %# Get the values in a2 corresponding %# to the ones in column 1 of a1 ans = 3 4 8 9 10 >> a2(a1(:,2)) %# Get the values in a2 corresponding %# to the ones in column 2 of a1 ans = 2 3 7 9
更多&回答...