How to make Duplicate values

I have matrix 1 example : W = [4 2 8 1 2 6 3 5 9]
and now matrix 2 example : Q = [1 2 1 2 3 2 1 2 1];
How to make duplicate W with Q values. And I want to get final matrix as R = [4 2 2 8 1 1 2 2 2 6 6 3 5 5 9]
please help me

 Accepted Answer

p = cumsum(accumarray(cumsum([1,Q])',1))';
R = W(p(1:end-1));
Note: If you have a zero in Q, the corresponding W value won't be copied at all in R.

More Answers (1)

Andhika - given your above example, you want to replicate each element in W for the number of times given in Q. So, for example, Q(1) is 1, and so W(1) is replicated once. More generally, W(k) is replicated Q(k) times. The arrayfun is a good to use as we can apply our "replicating" function to each of the k pairs as
result = cell2mat(arrayfun(@(w,q)repmat(w,1,q),W,Q,'UniformOutput',false));
We create a function that takes two inputs, the kth value from W as w, and the kth value from Q as q, then use repmat to replicate the w a q number of times. As the result is a cell (row) array, we convert it from a cell array to a matrix (row) using cell2mat.
Using your example W and Q vectors, we see that result is
W = [4 2 8 1 2 6 3 5 9];
Q = [1 2 1 2 3 2 1 2 1];
result = cell2mat(arrayfun(@(w,q)repmat(w,1,q),W,Q,'UniformOutput',false))
result =
4 2 2 8 1 1 2 2 2 6 6 3 5 5 9

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!