How to make Duplicate values
Afficher commentaires plus anciens
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
1 commentaire
per isakson
le 2 Nov 2014
Réponse acceptée
Plus de réponses (1)
Geoff Hayes
le 2 Nov 2014
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
1 commentaire
Andhika Fajar
le 2 Nov 2014
Catégories
En savoir plus sur Operators and Elementary Operations dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!