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

 採用された回答

Roger Stafford
Roger Stafford 2014 年 11 月 2 日

3 投票

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.

1 件のコメント

Andhika  Fajar
Andhika Fajar 2014 年 11 月 2 日
Thank u Roger Stafford. its work

サインインしてコメントする。

その他の回答 (1 件)

Geoff Hayes
Geoff Hayes 2014 年 11 月 2 日

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

1 件のコメント

Andhika  Fajar
Andhika Fajar 2014 年 11 月 2 日
Thank u Geoff Hayes. its work too

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by