codeAligned
codeAligned

Reputation: 189

Matlab coding for circulant matrix

I have this Matlab function from van Loan's book Introduction to Scientific Computation. It produces a matrix C where each row is the previous row with every element shifted by one to the right. I want to modify it so that the shift is to the right but I am having some trouble with the logic.

In particular, does the loop below make sense for right shift?

for i=2:n
C(i,:)=[C(i-1, n-2) C(i-1, 1:n-1)];
end


function C= circulantShift(a) %shifts to left
a=[1 2 3 4];
n=length(a);
C=zeros(n,n);
C(1,:)=a;
for i=2:n
   C(i, :)=[C(i-1, n) C(i-1, 1:n-1)];
end

Upvotes: 0

Views: 677

Answers (2)

Pet Detective
Pet Detective

Reputation: 86

First: the function circulantShift(a) shifts to the right, not the left.

The logic is as follows: In matlab [a b] does a horizontal concatenation. So [C(i-1, n) C(i-1, 1:n-1)] builds a line that consists of the nth (last) number in the row above, followed by the first 1:n-1 numbers in the row above. This is plainly a circular shift to the right.

If you want to shift to the left, you do the reverse. You take the 2nd to nth numbers from the row above, followed by the first number from the row above. Like this:

[C(i-1, 2:n) C(i-1, 1)]

Upvotes: 1

beaker
beaker

Reputation: 16811

In order to shift to the left you need to use:

C(i,:)=[C(i-1, 2:n) C(i-1, 1)];


C =

   1   2   3   4
   2   3   4   1
   3   4   1   2
   4   1   2   3

Upvotes: 1

Related Questions