6 Functions [10 marks]
Some important computational problems rely on performing a circular shift of the elements in a vector. A circular shift of a vector x
by n
positions produces a new vector where the elements of the vector are formed by shifting the elements of x
by n
positions to the right. Elements that are shifted past the end of the vector wrap around to the front of the vector. For example, suppose that the vector x
has the following values:
1, 2, 3, 4, 5, 6, 7, 8
A circular shift of x
by 0 positions returns a new vector that is equal to x
.
A circular shift of x
by 1 position returns the following vector:
8, 1, 2, 3, 4, 5, 6, 7
Notice that the 8 has wrapped around to the front of the new vector.
A circular shift of x
by 2 positions returns the following vector:
7, 8, 1, 2, 3, 4, 5, 6
Notice that the 7 and 8 have wrapped around to the front of the new vector.
A circular shift of x
by 7 positions returns the following vector:
2, 3, 4, 5, 6, 7, 8, 1
A circular shift of x
by 8 positions returns a new vector that is equal to x
because x
has 8 elements.
A circular shift of x
by 9 positions produces the same result as a circular shift of 1 position (in the case where x
has 8 elements).
If n
is negative then the elements are shifted to the left instead of to the right. For example, a circular shift of x
by -2 positions returns the following vector:
3, 4, 5, 6, 7, 8, 1, 2
Observe that in this case, a shift of -2
positions is equivalent to a shift of 6
positions.
Create a function that computes the circular shift of a row vector x
by n
positions.
Your function should satisfy the following constraints:
- it should be named
cshift
- it should return one value
v
(the vector obtained by circularly shifting the input vectorx
byn
positions) - it should have two input values
x
(a row vector) andn
(an integer number of positions to shiftx
by)
Your function must not use the MATLAB function circshift
.
Your function should work for all non-empty row vectors x
.
You will receive part marks if your function works correctly only for positive values of n
.
6.1 Example usage
x = [2 8 12 15];
% y should equal [15 2 8 12]
y = cshift(x, 1)
% y should equal [12 15 2 8 ]
y = cshift(x, 2)
% y should equal [8 12 15 2]
y = cshift(x, 3)
% y should again equal [8 12 15 2]
y = cshift(x, -1)