creating a vector from a bin count

3 Ansichten (letzte 30 Tage)
einat covo
einat covo am 23 Mai 2019
Beantwortet: Rik am 23 Mai 2019
Hello,
I have a matrix I got from another source that look like:
[0 5; 1 2; 2 1]
I wish to get a vector like [0 0 0 0 0 1 1 2] .
Thanks
EC

Akzeptierte Antwort

Stephen23
Stephen23 am 23 Mai 2019
Bearbeitet: Stephen23 am 23 Mai 2019
R2015a or later:
>> M = [0 5; 1 2; 2 1];
>> repelem(M(:,1),M(:,2)).'
ans =
0 0 0 0 0 1 1 2
R2014b or earlier:
>> C = arrayfun(@(x,n)repmat(x,1,n),M(:,1),M(:,2),'uni',0);
>> [C{:}]
ans =
0 0 0 0 0 1 1 2

Weitere Antworten (1)

Rik
Rik am 23 Mai 2019
You could of course do this with a loop (or cellfun), but I think a more elegant solution is with cumsum instead.
data=[0 5; 1 2; 2 1];
delta=data(:,1)-[0;data(1:(end-1),1)];
change_pos=[0;cumsum(data(1:(end-1),2))]+1;
out=accumarray(change_pos,delta);
out=cumsum(out);
The idea in this code is to do this:
%repeat 0 for 4 entries, 1 for 1 entry, and don't repeat 2
[0 x x x x 1 x 2]
%by setting x to 0, cumsum will create the desired matrix

Kategorien

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

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by