How to sepeperate a set of data to a new matrix from two set of matrix
Show older comments
Let,
A= [1 2 3 4 6 7 8 9; 10 11 12 13 14 15 16 17; 17 18 19 20 21 22 23 24]
B=[9 1; 17 1; 24 2]
I want to create a new set of matrix (say, C and D) consisting all the row values from matrix A based on the condition specified for matrix B:
Let [Row, Column 1] of Matrix B = B (:,1) = has different values;
[Row, Column 2] of Matrix B = B (:,2) = 1 or 2;
Column 2 of Matrix B has the same elements as Column 9 of Matrix A.
if [Row, Column 2] of Matrix B = B (:,2) = 1, then copy the entire row value of Matrix A corresponding to the [Row, Column 1] of Matrix B to a new Matrix C and so on...
and if [Row, Column 2] of Matrix B = B (:,2) = 2, then copy the entire row value of Matrix A corresponding to the [Row, Column 1] of Matrix B to a new Matrix D and so on...
2 Comments
Geoff Hayes
on 12 Apr 2015
Column 2 of Matrix B has the same elements as Column 9 of Matrix A.
From your above example, it would seem that Column 1 of B has the same elements as column 9 of A.
Ravi - you need to clarify the rules and provide examples at each step so that it is clear to you and us what you are trying to do.
Accepted Answer
More Answers (1)
Geoff Hayes
on 15 Apr 2015
Ravi - try the following
A = [1 2 3 4 6 7 8 9; 10 11 12 13 14 15 16 17; 17 18 19 20 21 22 23 24];
B = [9 1; 17 1; 24 2];
C = [];
% loop over each row of B
for k=1:size(B,1)
% if the second column of row k is one
if B(k,2) == 1
% get the row and column indices of A which match on B(k,1)
[ridx,cidx] = find(A == B(k,1));
if ~isempty(ridx)
% copy the row(s) of A to C
C = [C ; A(ridx,:)];
end
end
end
The result of running the above is
C =
1 2 3 4 6 7 8 9
17 18 19 20 21 22 23 24
10 11 12 13 14 15 16 17
We get three rows since 17 (the first element of the second column of B) is found in rows 2 and 3 of A.
1 Comment
Ravi
on 15 Apr 2015
Categories
Find more on Loops and Conditional Statements 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!