How to shift entries in a vector by the value of the number in that entry?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Tim David
am 19 Mär. 2021
Kommentiert: Stephen23
am 19 Mär. 2021
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.
1 Kommentar
Akzeptierte Antwort
Stephen23
am 19 Mär. 2021
T = [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)
2 Kommentare
Stephen23
am 19 Mär. 2021
"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.
Siehe auch
Kategorien
Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!