column circular permutaion on a matrix

2 visualizaciones (últimos 30 días)
Abhishek Bakhla
Abhishek Bakhla el 20 de Abr. de 2020
Comentada: Abhishek Bakhla el 23 de Abr. de 2020
How can I move all the elements of a particular column circulary upwards or circularly downwards by some shift s. I have a matrix A = [ 1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] and shift columns 1, 2, 3 and 4 by shifts 2, 1 , 3 and 2 respectively then I get the matrix A as A = [9 6 15 12; 13 10 3 16; 1 14 7 4; 5 2 11 8].

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 20 de Abr. de 2020
Try this
A = [ 1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16];
B = [9 6 15 12; 13 10 3 16; 1 14 7 4; 5 2 11 8];
shift = [2, 1, 3, 2];
C = A; % make a copy
for i=1:numel(shift)
C(:,i) = circshift(C(:,i), -shift(i));
end
Result
>> isequal(B, C)
ans =
logical
1
  2 comentarios
Abhishek Bakhla
Abhishek Bakhla el 21 de Abr. de 2020
thank you.
Ameer Hamza
Ameer Hamza el 21 de Abr. de 2020
Glad to be of help.

Iniciar sesión para comentar.

Más respuestas (2)

Ilian
Ilian el 20 de Abr. de 2020
If you just want to rotate the rows this could work:
s = -3; % shift (both positive and negative values work)
rows = size(A,1);
B = [A(mod(s-rows,rows)+1:end,:); A(1:mod(s-rows,rows),:)];

Stephen23
Stephen23 el 21 de Abr. de 2020
No loops:
>> A = [1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16];
>> S = [2,1,3,2]; % shifts
>> [R,C] = ndgrid(1:4,1:4);
>> B = A(sub2ind([4,4],1+mod(S+R-1,4),C))
B =
9 6 15 12
13 10 3 16
1 14 7 4
5 2 11 8

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by