group in a small vector

조회 수: 7 (최근 30일)
Beatriz Dueñas Muñoz
Beatriz Dueñas Muñoz 2020년 3월 23일
댓글: Beatriz Dueñas Muñoz 2020년 3월 24일
I have a vector
A=[1,0,0,1,1,1];
I need to pass this vector to a new one taking groups of 3 element so
B = [100, 111]
Does someone know how could I do this?
Thank you

채택된 답변

Sindar
Sindar 2020년 3월 24일
편집: Sindar 2020년 3월 24일
Ok, here is a way:
A=[1,0,0,1,1,1];
% turn A into a 1x6 string array
tmp=string(A);
% reshape into a 3xN string array, then transpose to Nx3
tmp=reshape(tmp,3,[])';
% combine each row, leaving a Nx1 string array
tmp=join(tmp,'');
% convert back to a Nx1 numeric array, then transpose to 1xN
B = double(tmp)';
or, in one line:
B = double(join(reshape(string(A),3,[])',''))'
  댓글 수: 2
Sindar
Sindar 2020년 3월 24일
Should work for any A with a multiple of 3 elements, and error otherwise, e.g.,
Error using reshape
Product of known dimensions, 3, not divisible into total number of elements, 8.
Beatriz Dueñas Muñoz
Beatriz Dueñas Muñoz 2020년 3월 24일
thank you so much!!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by