Create variables for sub matrices from selected columns 0f a larger matrix
Mostrar comentarios más antiguos
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
1 comentario
Stephen23
el 19 de Oct. de 2017
"I am trying to create matrix variables TD_1 TD_2 TD_3"
Which is exactly how beginners write slow, complex, buggy code.
Respuestas (1)
Andrei Bobrov
el 19 de Oct. de 2017
Editada: Andrei Bobrov
el 19 de Oct. de 2017
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)});
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!