How can I make these separate for loops into a nested for loop together?

1 view (last 30 days)
clc, clear
A = [1:11; 2:12; 3:13; 4:14; 5:15; 6:16; 7:17 ]
[M N] = size(A);
%
for i = 1:M
Ax = [A(i, N - 5 + 1:N) A(i, 1:N - 5)];
Ax(1,(1:5)) = 0;
k(i,:) = Ax;
end
%
for j = 1:N
Ay = [k(1+2:M,j);
k(1:2,j)];
Ay(end-1:end) = 0;
k(:,j) = Ay;
end
This is the output: A is the starting matrix, and k is after everything is shifted over 5 and up 2. But I can't figure out how to do it as a nested for loop together.
A =
1 2 3 4 5 6 7 8 9 10 11
2 3 4 5 6 7 8 9 10 11 12
3 4 5 6 7 8 9 10 11 12 13
4 5 6 7 8 9 10 11 12 13 14
5 6 7 8 9 10 11 12 13 14 15
6 7 8 9 10 11 12 13 14 15 16
7 8 9 10 11 12 13 14 15 16 17
k =
0 0 0 0 0 3 4 5 6 7 8
0 0 0 0 0 4 5 6 7 8 9
0 0 0 0 0 5 6 7 8 9 10
0 0 0 0 0 6 7 8 9 10 11
0 0 0 0 0 7 8 9 10 11 12
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0

Answers (2)

Sally Al Khamees
Sally Al Khamees on 22 Dec 2016
Try this:
[r,c]=size(A);
k = zeros(r,c);
for i=1:(r-2)
for j = 6:c
k(i,j) = A(i+2,j-5);
end
end
k

Roger Stafford
Roger Stafford on 22 Dec 2016
You don’t need for-loops at all.
k = zeros(size(A));
k(1:5,6:11) = A(3:7,1:6);

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!