How to shift the vector element inside of the vector?

조회 수: 6 (최근 30일)
Kundera
Kundera 2017년 6월 9일
답변: Star Strider 2017년 6월 9일
Is there any fast way I can shift a vector, for example given:
a = [1 2 3 4 5]
How can I shift of two positions the vector in such a way that I get:
a = [0 0 1 2 3]
Thanks.
  댓글 수: 1
Adam
Adam 2017년 6월 9일
doc circshift
will do a circular shift, but I'm not aware of a builtin method that will put 0s in the first locations instead so you may have to do that yourself.

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

채택된 답변

Star Strider
Star Strider 2017년 6월 9일
Another option:
a = [1 2 3 4 5];
as = zeros(size(a));
as(end-2:end) = a(1:3)
as =
0 0 1 2 3

추가 답변 (2개)

Adam
Adam 2017년 6월 9일
편집: Adam 2017년 6월 9일
nShift = 2;
a = circshift( [a zeros(1,nShift )], nShift );
a = a(1:end-nShift )
will work I guess

John D'Errico
John D'Errico 2017년 6월 9일
I'd just do it in 2 steps.
1. Use circshift.
2. Replace the elements at the beginning with zeros as necessary. If the shift was negative, then replace elements at the end.
So write a little helper function that does this for you, if you will be doing the action often. This is how MATLAB works. If you need something that is not there, then write the tools you need to expand MATLAB in the direction you want it to go.

카테고리

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