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
1 件のコメント
per isakson
2014 年 11 月 2 日
採用された回答
その他の回答 (1 件)
Geoff Hayes
2014 年 11 月 2 日
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
カテゴリ
ヘルプ センター および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!