Repetition of elements in a matrix

조회 수: 7 (최근 30일)
Danish Nasir
Danish Nasir 2021년 9월 4일
댓글: Walter Roberson 2021년 9월 4일
Suppose i have a matrix A= [25 21 ] . I want to repeat elements by 4 and 2 times respectively. Repeat=[4 2]. However the repeated values will be in proportion i.e. Proportion=[8 17]. The sum of proportion repeated element will be equal to A matrix elements. It means that final matrix will be B= [8 8 8 1 17 4].
(25=8+8+8+1 , 21=17+4 )
Pls suggest code to generate matrix B

채택된 답변

Walter Roberson
Walter Roberson 2021년 9월 4일
A = [25 21 ]
A = 1×2
25 21
Repeat = [4 2]
Repeat = 1×2
4 2
Proportion = [8 17]
Proportion = 1×2
8 17
leftover = A - Proportion .* (Repeat-1);
toRepeat = reshape([Proportion; leftover],1,[]);
repeatCount = reshape([Repeat-1; ones(1,length(Repeat))],1,[]);
B = repelem(toRepeat, repeatCount)
B = 1×6
8 8 8 1 17 4
  댓글 수: 2
Danish Nasir
Danish Nasir 2021년 9월 4일
It nearly solved my problem. I just want to add one complexity in the problem. There is a 3rd element in the matrix which i do not want to propotionate
A=[25 21 30]
Repeat=[4 2 1]
Proportion=[8 17 30].
B=[8 8 8 1 17 4 30]
Can you suggest how to generate B?
Walter Roberson
Walter Roberson 2021년 9월 4일
The code already handles that.
A = [25 21 30]
A = 1×3
25 21 30
Repeat = [4 2 1]
Repeat = 1×3
4 2 1
Proportion = [8 17 30]
Proportion = 1×3
8 17 30
leftover = A - Proportion .* (Repeat-1);
toRepeat = reshape([Proportion; leftover],1,[]);
repeatCount = reshape([Repeat-1; ones(1,length(Repeat))],1,[]);
B = repelem(toRepeat, repeatCount)
B = 1×7
8 8 8 1 17 4 30

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by