0

I have a matrix train3.

1    2    3    4    5    6    7
2   12   13   14   15   16   17
3   62   53   44   35   26   17
4   52   13   24   15   26   37

I want to select only those rows of whose 1st columns contain specific values (in my case 1 and 2).

I have tried the following,

>> train3
train3 =
    1    2    3    4    5    6    7
    2   12   13   14   15   16   17
    3   62   53   44   35   26   17
    4   52   13   24   15   26   37

>> ind1 = train3(:,1) == 1
ind1 =
   1
   0
   0
   0

>> ind2 = train3(:,1) == 2
ind2 =
   0
   1
   0
   0

>> mat1 = train3(ind1, :)
mat1 =
   1   2   3   4   5   6   7

>> mat2 = train3(ind2, :)
mat2 =
    2   12   13   14   15   16   17

>> mat3 = [mat1 ; mat2]
mat3 =                                                                                                                                         
    1    2    3    4    5    6    7
    2   12   13   14   15   16   17

>>

Is there any better way to do this?

2 Answers 2

2

Presumably you are trying to get mat3 in a single step which you can do with:

mat3 = train3(train3(:,1)==1 | train3(:,1)==2,:)
Sign up to request clarification or add additional context in comments.

Comments

2

A more general way to do this would be to use ismember to get all of the rows that match the values in a list:

train3 =[
    1    2    3    4    5    6    7
    2   12   13   14   15   16   17
    3   62   53   44   35   26   17
    4   52   13   24   15   26   37];

chooseList = [1 2];

colIndex = ismember(train3(:, 1), chooseList);

subset = train3(colIndex, :);

subset =

     1     2     3     4     5     6     7
     2    12    13    14    15    16    17

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.