How to shift just the outer loop in an array?

조회 수: 5 (최근 30일)
LEP
LEP 2015년 6월 2일
답변: Andrei Bobrov 2015년 6월 2일
The script should assume an m-by-n array A (m, n >= 2) is assigned in the Command Window. The value mover should also be assigned. The script should rotate all of the values on the outer loop of the array by mover spots clockwise and call the output A_out.
Example executions follow:
>> A = [1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15; 16 17 18 19 20]; mover = 2;
>> script25_drew_murray
A_out =
11 6 1 2 3
16 7 8 9 4
17 12 13 14 5
18 19 20 15 10
I have written this script so far. I managed to rotate the outer loop according to the mover spots. How do I keep just the middle section of the matrix if this section size is subject to change? Also, how do I put the rotated loop array back in the matrix form given?
dim = size(A);
m = dim(1);
n = dim(2);
B= zeros(m,n)+A
outerloop = [A(1,1:end-1),A(:,n).',A(m,fliplr(1:end-1)),A(fliplr(2:end-1),1).']
rotatedloop = circshift(outerloop,mover,2)

답변 (1개)

Andrei Bobrov
Andrei Bobrov 2015년 6월 2일
A = [1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15; 16 17 18 19 20], mover = 2
[m,n] = size(A);
i0 = [(1:m)';(2:n)'*m;m*n - (1:m-1)';(n-2:-1:1)'*m+1];
A = a;
A(i0) = A(circshift(i0,-mover))
A(i0) = A(circshift(i0,mover)) %come back

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by