tags:

views:

57

answers:

2

hi,

I was wondering what best practices are for the following:

i have two matrices, a1(500,40) and a2(1,500) and for a1, which is boolean, i want to separate out the arrays depending on the values in a particular column (ie. 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 + a2, doing the logical test and then separating them again, but was wondering if there is a commonly used method for something like this? (very new to matlab)

thanks!

A: 
newval=a1(:,5); %equals to the 5th column
Pentium10
flyingcrab
+3  A: 

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
gnovice
interesting - i think a mod of this will work! thanks!
flyingcrab

related questions