circshift columns of array by different shift size

조회 수: 16 (최근 30일)
Sidafa
Sidafa 2015년 4월 10일
댓글: omar A.alghafoor 2020년 10월 12일
I'm trying to do the following with arrayfun and circshift
s_dfp = magic(4);
s_hh1p = circshift(s_dfp(:,1),[1 -1]);
s_hh2p = circshift(s_dfp(:,2),[1 -2]);
s_hh3p = circshift(s_dfp(:,3),[1 -3]);
s_hh4p = circshift(s_dfp(:,4),[1 -4]);
HH = [s_hh1p s_hh2p s_hh3p s_hh4p];
s_dfp =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
HH =
4 14 15 1
16 2 3 13
5 11 10 8
9 7 6 12
Each column is shifted by its column number. I would like to do this for arbitrary size.
Thanks in advance.
  댓글 수: 1
Image Analyst
Image Analyst 2015년 4월 10일
This first column is shifted down 1 because the first element, 16, is now in row 2 instead of row 1. However if you were to circularly shift column 2 down, the top element, 2, would be in row 3 instead of row 1. But you have it in row 2. And in the third column, then 3 shifted down 3 rows would be in row 4, not row 2. Finally if you were to circularly shift column 4 down 4, the 13 would land in the same spot (row 1). So, other than the first column being shifted down 1, I can't see what you're doing. In fact, columns 1, 2, 3, and 4 are all shifted down by 1 row, NOT by their column number.

댓글을 달려면 로그인하십시오.

채택된 답변

Jon
Jon 2015년 4월 10일
I think this does what you want.
HH=cell2mat(arrayfun(@(k) circshift(d(:,k),k),1:size(d,2),'uni',0))
HH =
4 7 10 13
16 14 6 8
5 2 15 12
9 11 3 1)
You may need to change the sign of the second k in the circshift command to get the elements to move in the direction you want.

추가 답변 (2개)

Image Analyst
Image Analyst 2015년 4월 10일
I don't see that what you did matches what you said. But anyway, try this and see if it does what you want:
s_dfp = magic(4)
outputMatrix = s_dfp; % Initialize.
[rows, columns] = size(s_dfp);
for col = 1 : columns
% Extract just this column only.
thisColumn = s_dfp(:, col);
% Shift it down "col" rows.
shiftedColumn = circshift(thisColumn, -col)
% Put it back in
outputMatrix(:, col) = shiftedColumn;
end
% Print to command window
outputMatrix
  댓글 수: 5
Image Analyst
Image Analyst 2020년 10월 12일
You'd need to keep track of how much you shifted each column and shift it in the opposite direction. Or just keep your original image (don't delete it!).
omar A.alghafoor
omar A.alghafoor 2020년 10월 12일
thank you

댓글을 달려면 로그인하십시오.


Star Strider
Star Strider 2015년 4월 10일
One possibility is to vectorise it and use an anonymous function:
csm = @(Mtx,Col) circshift(Mtx(:,Col),[1 1-Col]); % Arbitrary Matrix
callcsm = @(Mtx) csm(Mtx, 1:size(Mtx,2));
s_dfp = magic(4);
HH = callcsm(s_dfp);
The ‘csm’ (circularly shift matrix) function does the shifting, and the ‘callcsm’ function requires only the matrix name to produce the vectorised result.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by