Adding Zeroes and Ones into a Vector

조회 수: 1 (최근 30일)
Hollis Williams
Hollis Williams 2019년 5월 19일
편집: dpb 2019년 5월 22일
I have a 1x300 vector and would like to make it into a 1x400 vector by inserting a 0 after every third element, a 0 after every sixth element and a 1 after the ninth element and then after the twelfth element insert a 0 and repeat the pattern.
So for example if I have
0 0 1 0 1 0 1 0 0
this would become
0 0 1 0 0 1 0 0 1 0 0 1
and so on.

채택된 답변

dpb
dpb 2019년 5월 19일
편집: dpb 2019년 5월 22일
>> v=reshape([reshape(v,[],3),[0 0 1].'].',1,[])
v =
0 0 1 0 0 1 0 0 1 0 0 1
>>
To generalize, repmat the augmentation vector as many times as needed.
>> v=reshape([reshape(v,[],3),repmat([0 0 1].',numel(v)/9,1)].',1,[])
v =
0 0 1 0 0 1 0 0 1 0 0 1
>>
ADDENDUM: To make the generalizaton more clear perhaps...
lenStr=3; % length prior to insertion point
vaug=[0 0 1].'; % the augmenting vector
lenAug=numel(vaug); % length of augmentation vector
v=reshape([reshape(v,[],lenStr),repmat(vaug,numel(v)/(lenStr*lenAug),1)].',1,[])
  댓글 수: 6
Hollis Williams
Hollis Williams 2019년 5월 21일
The code above didn't seem to give the desired result. Let's just simplify and say that I have a 1x108 vector and after every third vector I just went to inset a 1 so that I end up with a 1x144 vector, what would be the simple way of doing this?
dpb
dpb 2019년 5월 21일
Same logic works with the augmentation vector being only 1 element, too:
reshape([reshape(v,[],3) ones(108/3,1)].',1,[])
You just have to compute the repeat factor correctly dependent upon the length being added--how many rows does it add each time?
The above with the hardcoded '9' was specific for the original question of 3.

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

추가 답변 (1개)

Jos (10584)
Jos (10584) 2019년 5월 21일
Inserting elements at specific locations is not trivial. Years ago I wrote a function INSERTROWS that does this

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by