circshift function working explanation needed

68 views (last 30 days)
Manu Chaudhary on 16 Jan 2022
Commented: Manu Chaudhary on 16 Jan 2022
Completely new to matlab. Studying some sample codes.
% bitget and num2str and circular shift
x = 0b10011010u8 % x is 10011010
value3= bitget(x, 8:-1:1) % x's binary representation is 10011010
formatSpec4= '%d'
s4= num2str(value3, formatSpec4);
s5= s4;
s5(1:4) = circshift(s5(1:4),-1);
s6= s5;
Not able to understand the syntax and functionality of circshift. Thank in advance
Please explain me the functionality of circshift.
0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

Accepted Answer

Voss on 16 Jan 2022
circshift(s,d) for a vector s and positive integer d shifts the elements of s to the right by d amount, wrapping back to the beginning when they go off the end (thats why it's called circular). If d is negative, elements are shifted to the left by -d amount.
It's easier to see what it does with a few examples in MATLAB rather than a few sentences in English.
s = [10 20 30 40 50] % original vector s
s = 1×5
10 20 30 40 50
circshift(s,1) % shift s right by 1, last element wraps around to become first
ans = 1×5
50 10 20 30 40
circshift(s,-1) % shift s left by 1, first element wraps around to become last
ans = 1×5
20 30 40 50 10
circshift(s,2) % right by 2
ans = 1×5
40 50 10 20 30
circshift(s,-4) % left by 4
ans = 1×5
50 10 20 30 40
circshift(s,5) % shifting by the length of the vector returns the original vector
ans = 1×5
10 20 30 40 50
In your code, the first 4 elements of s5 are shifted left by one place and stored back into s5 as the first 4 elements (and the remaining elements are untouched):
s5 = [1 2 3 4 5 6 7 8]
s5 = 1×8
1 2 3 4 5 6 7 8
s5(1:4) = circshift(s5(1:4),-1)
s5 = 1×8
2 3 4 1 5 6 7 8
1 CommentShow -1 older commentsHide -1 older comments
Manu Chaudhary on 16 Jan 2022
Thank you.

Sign in to comment.

More Answers (1)

Walter Roberson on 16 Jan 2022
M = (10:10:40).' + (1:9)
M = 4×9
11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 41 42 43 44 45 46 47 48 49
circshift(M, -1)
ans = 4×9
21 22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 41 42 43 44 45 46 47 48 49 11 12 13 14 15 16 17 18 19
You can see that this is the same as
[M(2:end,:); M(1,:)]
And more generally, circshift(M, -K) would be
[M(K+1:end,:); M(1:K,:)]
2 CommentsShow NoneHide None
Walter Roberson on 16 Jan 2022
For vectors:
M = 1 : 9
M = 1×9
1 2 3 4 5 6 7 8 9
circshift(M, -1)
ans = 1×9
2 3 4 5 6 7 8 9 1
which is [M(2:end),M(1)] .
When you specify a scalar for the shift, then circshift operates on the first non-singleton dimension.
Manu Chaudhary on 16 Jan 2022
Thank you.

Sign in to comment.

Categories

Find more on Watermarking in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!