Filter löschen
Filter löschen

How to repeat rows of matrix?

1 Ansicht (letzte 30 Tage)
Tom
Tom am 13 Jun. 2013
Hi,
I have a matrix and a vector indicating how many times the corresponding lines in the matrix should appear. I'd like to turn this into a single matrix.
For example:
M= 1 2 V=1
2 3 2
4 3 1
2 4 2
should become
M =1 2
2 3
2 3
4 3
2 4
2 4
Does anyone have advice on how to accomplish this? Many thanks.

Akzeptierte Antwort

Matt Kindig
Matt Kindig am 13 Jun. 2013
Bearbeitet: Matt Kindig am 13 Jun. 2013
One way:
f = @(k) repmat(M(k,:), round(V(k)), 1);
MM = cell2mat(arrayfun(f, (1:length(V))', 'UniformOutput', false));

Weitere Antworten (4)

Roger Stafford
Roger Stafford am 13 Jun. 2013
Here's yet another possibility:
p = accumarray(cumsum([1;v]),1);
M = M(cumsum(p(1:end-1)),:);

Matt J
Matt J am 13 Jun. 2013
Bearbeitet: Matt J am 13 Jun. 2013
c=cumsum(V);
[~,i]=max(bsxfun(@le,1:c(end),c));
MM=M(i,:),

Azzi Abdelmalek
Azzi Abdelmalek am 13 Jun. 2013
out=cell2mat(arrayfun(@(x) repmat(M(x,:),V(x),1),[1:numel(V)]','un',0))

Matt J
Matt J am 13 Jun. 2013
Bearbeitet: Matt J am 13 Jun. 2013
c=cumsum(V);
z=sparse(1,c(end)+1-c,1,1, c(end));
m=fliplr(cumsum(z))
Mnew = M(m(1)+1-m,:),

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by