2010-02-07 39 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

相關問題