Split array into some equal and some unequal length sections

조회 수: 4 (최근 30일)
Phil Roberts
Phil Roberts 2018년 11월 27일
답변: Bruno Luong 2018년 11월 27일
Hello,
I have an array which is 41683 rows long. I wish to split this into as many new arrays of 60 rows as possible.
However, 41683 does not divide by 60 into whole numbers (694.717); hence I need to write some code that will result in 694 columns x 60 rows and a final columns for the remaining 43 rows (0.717 x 60).
I have tried using:
a = [1:41683]'
b = reshape(a,60,[]) but because 41863 is not completely divisible by 60, I get an error.
Can anyone help please?
Many thanks,
Phil

채택된 답변

Andrei Bobrov
Andrei Bobrov 2018년 11월 27일
편집: Andrei Bobrov 2018년 11월 27일
n = 60;
ii = (1:numel(a))';
out = accumarray([rem(ii-1,n)+1,ceil(ii/n)],a,[],[],nan);
or
out = reshape([a;nan(mod(-numel(a),n),1)],n,[]);

추가 답변 (2개)

madhan ravi
madhan ravi 2018년 11월 27일
Convert the array to cell and then use reshape()
  댓글 수: 2
Phil Roberts
Phil Roberts 2018년 11월 27일
Hello,
I tried this and it did not work.
Any other thoughts?
Many thanks in advance.
madhan ravi
madhan ravi 2018년 11월 27일
show what you are trying

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


Bruno Luong
Bruno Luong 2018년 11월 27일
a = [1:41683]'
n = size(a,1);
blk = 60;
lgt = ones(1,floor(n/blk))*blk;
r = n-sum(lgt);
if (r > 0) lgt(end+1) = r;
b = mat2cell(a,lgt,1)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by