how to swap some vector value?
조회 수: 6 (최근 30일)
이전 댓글 표시
Dear all
I have the following vector
S=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...... ]
what I would like to do is to change 1 and 2 position to be after 10 then to 11 and 12 after 20 and etc.
so S will be like S= [3 4 5 6 7 8 9 10 1 2 13 14 15 16 17 18 19 20 11 12 ....]
I hope that the problem is well explained.
Thanks a lot in advance for your contribution
댓글 수: 0
답변 (3개)
Star Strider
2021년 8월 24일
S=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
Sr = reshape(S,10,[])
Src = circshift(Sr,-2,1)
Result = reshape(Src,1,[])
Note — ‘S’ must always have a length that is an integer multiple of 10 for this to work. An alternative to reshape if that is not the situation is the Signal Processing Toolbox buffer function, however the results of the last column might not be the desired result.
.
댓글 수: 0
Wan Ji
2021년 8월 24일
편집: Wan Ji
2021년 8월 24일
A general answer is
S = 1:100; %
count = 1;
copyLength = 2; %
copyStep = 10; % copyStep>copyLength
while count<=numel(S)-copyLength
if(count==1)
copySeg = S(count:count+copyLength-1);
S(count:count+copyLength-1) = [];
count = count + copyStep - copyLength;
else
copyTemp = S(count:count+copyLength-1);
S(count:count+copyLength-1) = copySeg;
copySeg = copyTemp;
count = count + copyStep;
end
end
if(count-1<=numel(S))
nLen = count + copyLength -1 - numel(S);
S = [S, ones(1,nLen)];
S(count:count+copyLength-1) = copySeg;
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!