开发者

How can I extract values from two matrices based on the values in one of them?

I was wondering what best practices are for the following:

I have two matrices, a1 (500-by-40) and a2 (1-by-500). For a1, which is boolean, I want to separate out the arrays depending on the values in a particular column (i.e. true or false). I would also need to separate the corresponding entry in a2.

I can do this with a couple of loops, or perhaps even by concatenating a1 and 开发者_运维知识库a2, doing the logical test and then separating them again, but was wondering if there is a commonly used method for something like this?


This is a guess, but it sounds like for the true entries in each column in a1 you want to extract the corresponding values in a2. Since you said a1 is a boolean (known as a logical type in MATLAB) you can use logical indexing in the following way:

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
...

Here's an example:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜