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

1 次查看(过去 30 天)
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

回答(2 个)

Sally Al Khamees
Sally Al Khamees 2016-12-22
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 2016-12-22
You don’t need for-loops at all.
k = zeros(size(A));
k(1:5,6:11) = A(3:7,1:6);

类别

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