Hi there
I have a matrix that i need to make twice as long. i.e i need to double the length of columns. eg i need:
[0 1 0 0]
[0 2 0 0]
to become:
[0 1 0 0]
[0 1 0 0]
[0 2 0 0]
[0 2 0 0]
Thanks

댓글 수: 1

Stephen23
Stephen23 2022년 1월 3일
편집: Stephen23 2022년 1월 5일
A = [0,1,0,0;0,2,0,0]
A = 2×4
0 1 0 0 0 2 0 0
B = repelem(A,2,1)
B = 4×4
0 1 0 0 0 1 0 0 0 2 0 0 0 2 0 0

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

 채택된 답변

Star Strider
Star Strider 2019년 1월 23일
편집: Star Strider 2019년 1월 23일

0 개 추천

Try this:
M = [0 1 0 0
0 2 0 0];
M2 = repmat(M, 1, 2);
M2 = reshape(M2', [], 4)'
producing:
M2 =
0 1 0 0
0 1 0 0
0 2 0 0
0 2 0 0
You could combine both calculations into a one-line calcualtion if you want to.
EDIT —
Generally, for ‘N’ repitions, the code becomes:
N = 4; % Number Of Repititions
Mn = repmat(M, 1, N)
Mn = reshape(Mn', [], 2*N)'
producing:
Mn =
0 1 0 0
0 1 0 0
0 1 0 0
0 1 0 0
0 2 0 0
0 2 0 0
0 2 0 0
0 2 0 0

댓글 수: 3

Matthew Allison
Matthew Allison 2022년 1월 3일
elegant solution.
to make this a truly generic solution, the 2*N should be replaced by m*N, where m is the number of rows being duplicated. The 2 assumes that the original array has only 2 rows.
Stephen23
Stephen23 2022년 1월 3일
편집: Stephen23 2022년 1월 3일
@Matthew Allison if you think that is elegant, just wait until you see REPELEM in action:
M = [0,1,0,0;0,2,0,0]
M = 2×4
0 1 0 0 0 2 0 0
Mn = repelem(M,2,1)
Mn = 4×4
0 1 0 0 0 1 0 0 0 2 0 0 0 2 0 0
REPELEM was introduced in R2015a, it is not clear why StarStrider avoided using it here.
Star Strider
Star Strider 2022년 1월 3일
편집: Star Strider 2022년 1월 4일
@Matthew Allison — Thank you!
@Stephen — Because I wanted to make it general enough to work with earlier versions as well.

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

추가 답변 (0개)

카테고리

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

태그

질문:

2019년 1월 23일

편집:

2022년 1월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by