How to seperate data from matrix based on a given condition

2 views (last 30 days)
A = [1 2 3 4 6 7 8 9 15; 10 11 12 13 14 15 16 17 18; 17 18 19 20 21 22 23 24 19; 10 11 12 13 14 15 16 24 18]
A =
1 2 3 4 6 7 8 9 15
10 11 12 13 14 15 16 17 18
17 18 19 20 21 22 23 24 19
10 11 12 13 14 15 16 24 18
B = [9 1; 17 1; 24 2; 15 1; 18 2; 19 1]
B =
9 1
17 1
24 2
15 1
18 2
19 1
Now the conditions are:
If Column 8 Row (1-3) and Column 9 Row (1-3) of Matrix A = 1 and 1 [see Column 2 Row (1-6) for corresponding Column 1 Row (1-6)], then copy entire corresponding row of Matrix A to a new Matrix C.
If Column 8 Row (1-3) and Column 9 Row (1-3) of Matrix A = (1 and 2) or (2 and 1) [see Column 2 Row (1-6) for corresponding Column 1 Row (1-6)], then copy entire corresponding row of Matrix A to a new Matrix D.
If Column 8 Row (1-3) and Column 9 Row (1-3) of Matrix A = 2 and 2 [see Column 2 Row (1-6) for corresponding Column 1 Row (1-6)], then copy entire corresponding row of Matrix A to a new Matrix E.

Accepted Answer

Guillaume
Guillaume on 16 Apr 2015
It's a bit tricky, not helped that you've got conditions for column 8 and 9 in the same matrix. Anyway, this should work:
%for each row of column 1 of B, find the rows of A where column 8 match
rows8 = arrayfun(@(v) find(A(:, 8) == v), B(:, 1), 'UniformOutput', false);
%same for column 9 of A
rows9 = arrayfun(@(v) find(A(:, 9) == v), B(:, 1), 'UniformOutput', false);
%create cell array that gives the corresponding value in column two of B for each value in rows8
criteria8 = arrayfun(@(b, r) ones(numel(r{:}), 1) * b, B(:, 2), rows8, 'UniformOutput', false);
%same for rows9
criteria9 = arrayfun(@(b, r) ones(numel(r{:}), 1) * b, B(:, 2), rows9, 'UniformOutput', false);
%expand the cell arrays into column vectors. This gets rid of the empty cells
rows8 = cell2mat(rows8);
criteria8 = cell2mat(criteria8); %guaranteed to have the same number of elements as rows8
rows9 = cell2mat(rows9);
criteria9 = cell2mat(criteria9); %guaranteed to have the same number of elements as rows9
%now fill up the destination matrices. intersect tells us which rows match both criteria of the destination
C = A(intersect(rows8(criteria8 == 1), rows9(criteria9 == 1)), :)
D = A(union(intersect(rows8(criteria8 == 2), rows9(criteria9 == 1)), intersect(rows8(criteria8 == 1), rows9(criteria9 == 2))) , :)
E = A(intersect(rows8(criteria8 == 2), rows9(criteria9 == 2)), :)
  3 Comments
Guillaume
Guillaume on 17 Apr 2015
All learned from the docs and by writing code. I don't know any reference, I'm afraid.

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!