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개)

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

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

질문:

2014년 11월 2일

댓글:

2014년 11월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by