MATLAB: How to sepeperate a set of data to a new matrix from two set of matrix

for loopsort data from a data matrix

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…

Best Answer

Here is a generic way of splitting the original matrix into submatrices according to your condition:
function C = splitmatrix(A, B, indexcol)
%indexcol: a scalar integer >=1
%A: a M x N matrix, with N >= indexcol. the elements of A(:, indexcol)) must be unique
%B: a P x 2 matrix. Column 1 of B must match one value of A(:, indexcol). Column 2 of B must be integer >= 1
%C: cell array output of size max(B(:, 2) x 1.
%C{k} is a matrix whose rows are the rows of A for which A(:, indexrow) is found in B(1, B(:, 2) == k)
%validate above preconditions
validateattributes(indexcol, {'numeric'}, {'scalar', 'integer', 'positive'});
validateattributes(A, {'numeric'}, {'2d'});
assert(size(A, 2) >= indexcol, 'indexcol is greater than the number of columns of A');
assert(numel(unique(A(:, indexcol))) == size(A, 1), 'some elements of A(:, indexcol) are non unique');
validateattributes(B, {'numeric'}, {'2d', 'ncols', 2});
assert(all(ismember(A(:, indexcol), B(:, 1))), 'some elements of B(:, 1) are not found in A:, indexcol)');
validateattributes(B(:, 2), {'numeric'}, {'integer', 'positive'}, '', 'second column of B');
%find the rows of A that match first column of B:
Arows = arrayfun(@(indexval) find(A(:, indexcol) == indexval), B(:, 1));
%concatenate Arows according to the index in B(:, 2):
rowsdestination = accumarray(B(:, 2), Arows, [], @(v) {v});
%split A according to the destination:
C = cellfun(@(rows) A(rows, :), rowsdestination, 'UniformOutput', false);
end