Reputation: 49
Given the following Problem: How can I achieve this? I am trying to shift the columns to the right, but I can only get them to shift to the left. I also cannot account for the column on the end being shifted to the front. I know I need to use some kind of temporary array, but I don't know how to implement it.
My code so far:
function [B] = column_shift()
A = input('Enter an nx6 matrix: ')
interimA = A(:,6);
for n = 1:5
A(:,n) = A(:,n+1);
interimA = A(:,1);
end
B = A
end
Upvotes: 2
Views: 1312
Reputation: 74940
You can just use circshift
:
%# shift by 1 along dimension 2
shiftedA = circshift(A,1,2);
Note: CIRCSHIFT has changed its definition. Earlier versions of Matlab only took one input argument, so you'd have to write circshift(A,[0,1])
(shift 0 along first, 1 along second dimension) to achieve the same result as above.
If you absolutely do need to use a for-loop, you can do the following:
shiftStep = 1;
%# create an index array with the shifted column indices
nCols = size(A,2);
shiftedIndices = circshift(1:nCols,shiftStep,2);
shiftedA = A; %# initialize the output to the same size as the input
%# for-loop could be replaced by shiftedA = A(:,shiftedIndices);
for iCol = 1:nCols
shiftedA(:,iCol) = A(:,iCol==shiftedIndices);
end
Upvotes: 3
Reputation: 586
I've made a modified and commented version of your code. Hope it helps! Just a few notes:
You were shifting the columns to the left because you were shifting with column n+1, when you should be shifting with n-1.
The column in the end is a special case that is handled before the for loop (if you really need to do everything inside a for loop, you can start the cycle on n = 1, check if the loop is in the first column, and handled that "special shift" there).
You don't really need the temporary array. You can create one if it helps you make the code more understandable, but in this case I haven't used one.
function [B] = column_shift()
A = input('Enter an nx6 matrix: ')
B = A;
B(:,1) = A(:,end); %copy the last column of A to the first column of B
for n = 2 : size(A,2) %starting on the second column of A, until the last column...
B(:,n) = A(:,n-1); %copy the column "n-1" on A to the column "n" in B
end
end
Upvotes: 0