2010-02-07 38 views
1

我想知道什么最好的做法是以下几点:如何根据其中一个值中的值从两个矩阵中提取值?

我有两个矩阵,a1(500-由-40)和a2(1 * 500)。对于布尔型的a1,我想根据特定列中的值(即true或false)分开数组。我还需要分开a2中的相应条目。

我甚至可以通过连接a1a2,做逻辑测试,然后再次将它们分开,但不知道是否有这样的事情一常用的方法有几个循环,或也许这样做呢?

回答

4

这是一个猜测,但它听起来就像是在每列要在a2提取相应的值真正的条目a1。既然你说a1是一个布尔值(被称为MATLAB一个logical型),您可以通过以下方式使用logical indexing

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 
+0

有趣 - 我认为这将工作的MOD!谢谢! – malangi 2010-02-08 00:01:35

0
newval=a1(:,5); %equals to the 5th column 
+0

感谢 - 我试图truevals = A1( :,5)&&(a1 == 1)但似乎没有工作 - 编号喜欢提取(行)只有当col值为真 – malangi 2010-02-07 23:19:57

相关问题