# FUNCTION shift of vector's position

10 views (last 30 days)
Commented: Chunru on 9 Dec 2021
ANYONE CAN HELP ME PLS TO CREAT THIS FUNCTION I TRIED TO DO IT BUT I COULDNT WITHOUT any toolbox functions of cycles
function rotated = rotateRight( vector, shift )
% Performs cyclic shift of vector's position - the ROR operation.
% Performs horizontal ROR, if a matrix is supplied, rotate all rows.
% The scalar shift specifies how many positions to rotate
% if negative, a ROL operation is performed.
% You cannot use any toolbox functions of cycles,
% just indexing.

Edited: Walter Roberson on 8 Dec 2021
rotated = zeros(1, size(vector, 2))
shift = mod(shift, size(vector, 2))
rotated(1:shift) = vector(end-shift+1:end)
rotated(shift+1:end) = vector(1:end-shift)
i did it in this way but is there anyone have another method how to do it with same conditionals
##### 2 CommentsShowHide 1 older comment
thank you it work perfect

### More Answers (2)

Chunru on 7 Dec 2021
Edited: Chunru on 7 Dec 2021
Here is some pseudo code:
%1. Let the vector index be idx = (0:n-1) + 1
%2. When rotating to right by "shift" (which can be +ve/-ve), the corresponding index becomes
% newIdx = mod((0:n-1) + shift, n) + 1;
% where mod implements the rotation.
%3. Get the rotated vector: y = vector(newIdx)
##### 2 CommentsShowHide 1 older comment
Chunru on 9 Dec 2021
Then
newIdx = mod((0:n-1) - shift, n) + 1;

Walter Roberson on 7 Dec 2021
Take a copy of what is about to be overwriten.
Use array subscripts to move the old data to the new positions. For example
A(:,1:5) = A(:,3:7);
Now write the saved data to the other end of the array, into the spots vacated, like A(:,6:7)