Create variables for sub matrices from selected columns 0f a larger matrix

I am trying to create matrix variables TD_1 TD_2 TD_3 and have them set to M(1) =[1 4 ;1 1],M(2)=[2 ; 2 ],M(3)=[2 5;3 3]. The matrices are constructed according to the 3 numbers in col 2. I want to save the matrices M(1),M(2),M(3)
a = sym('TD_%d', [1 3])
M=[1 2 3 4 5 ; 1 3 2 1 3]
for i = 1:3
indx=find(M(2, :)==i)% when i=1 indx= [1 4]
M(:,indx) % M=[1 4;1 1]
a(i)=M
end

Answers (1)

M = [1 2 3 4 5 ; 1 3 2 1 3];
b = unique(M(2,:));
n = numel(b);
TD = cell(n,1);
for ii = 1:n
TD{ii} = M(:,M(2, :) == b(ii));
end
or
TD = accumarray(M(2,:)',1:size(M,2),[],@(x){M(:,x)});
or in the general case
[~,~,c] = unique(M(2,:));
TD = accumarray(c,(1:size(M,2)),[],@(x){M(:,x)});

Asked:

on 18 Oct 2017

Edited:

on 19 Oct 2017

Community Treasure Hunt

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

Start Hunting!