How to shift entries in a vector by the value of the number in that entry?

조회 수: 2 (최근 30일)
For example, if i have a vector
T = [0, 0, 4, 0, 7, 0, 0, 5, 0, 9]
How would i go about moving every entry to the right by the number in that entry?
Ie: T(3) 4 spaces to the right, T(4) 0 spaces to the right, and T(8) 5 spaces to the right so that it overwrites the orginal T(3).
Thanks.

채택된 답변

Stephen23
Stephen23 2021년 3월 19일
T = [0, 0, 4, 0, 7, 0, 0, 5, 0, 9]
T = 1×10
0 0 4 0 7 0 0 5 0 9
N = numel(T);
X = 1+mod(T+(0:N-1),N);
for k = 1:N
T([k,X(k)]) = [0,T(k)];
end
disp(T)
0 7 5 0 0 0 4 0 9 0
  댓글 수: 2
Tim David
Tim David 2021년 3월 19일
This is good, thank you. Is there a way to repeat this multiple times? Ie this method used again on the new T vector, then again on the resultant T vector and so on?
Stephen23
Stephen23 2021년 3월 19일
"Is there a way to repeat this multiple times? Ie this method used again on the new T vector, then again on the resultant T vector and so on?"
Put it inside another loop.

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

추가 답변 (1개)

Robert U
Robert U 2021년 3월 19일
편집: Robert U 2021년 3월 19일
Hi Tim David,
you can apply circshift() to the data.
T = [0, 0, 4, 0, 7, 0, 0, 5, 0, 9];
shiftme = @(A,nShift) circshift(A,A(nShift));
shiftme(T,3)
Kind regards,
Robert

카테고리

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

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by