简体   繁体   中英

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

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

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

The logic is as follows: In matlab [ab] 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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM