How to arrange one row vector into a row x column matrix?

조회 수: 3 (최근 30일)
Miroslav Josic
Miroslav Josic 2017년 2월 7일
댓글: Miroslav Josic 2017년 2월 7일
Hi guys, I would appreciate your help on this problem. I have a row vector (M) of size 1x2108 which contains data for 62 countries and 34 industries for each country. So, column 1:34 is industry data for country 1, 35:68 country #2 etc. I just need to make a matrix which will be of a size 62x2108 and have data in following way: - row #1, columns 1:34 for country #1, elsewhere zeros - row #2, columns 35:68 for country #2, elsewhere zeros - row #3, columns 39:102 for country #3, elsewhere zeros etc.
So far, I used this code:
M_new=zeros(62,2108);
for i=1:62
for j=1:62
M_new(i,((j-1)*34+1):(j*34))=M(1,((j-1)*34+1):(j*34));
end
end
but I only get row vector copied 62 times in each row.
Best,
Miroslav

채택된 답변

Guillaume
Guillaume 2017년 2월 7일
M_new = [reshape(M, 34, 62); zeros(2108, 62)];
M_new = reshape(M_new(1:end-2108), 2108, [])'
No need for a loop.
However, I question the wisdom of using 62 times more memory to store the same information.
  댓글 수: 1
Miroslav Josic
Miroslav Josic 2017년 2월 7일
Hi Guillaume,
Thanks a lot for your quick reply, indeed it works perfectly. I was using loop for some other re-arrangements and it did not take much time so I tried to use it here again.
Best,
Miroslav

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

추가 답변 (1개)

KSSV
KSSV 2017년 2월 7일
You should have a look into reshape. Read about reshape
  댓글 수: 1
Miroslav Josic
Miroslav Josic 2017년 2월 7일
Hi KSSV,
Thanks for your hint. Guillaume proposed the solution and it managed to give me the exact output I needed.
In any case, thanks for your help!
Miroslav

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

카테고리

Help CenterFile Exchange에서 App Building에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by