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

조회 수: 1 (최근 30일)
Muhamed Polovina
Muhamed Polovina 2016년 12월 8일
편집: per isakson 2016년 12월 22일
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