I have 2 for commands, and only one works?:O

조회 수: 1 (최근 30일)
Matija Kosak
Matija Kosak 2018년 7월 6일
답변: Guillaume 2018년 7월 6일
I have 2 matrix, for example A(nx3) and B(mx3), and in the same code I have to change with same for loop something in them. But only changes one, other stays the same, what can be problem?
Y and Z can be any numbers that can be divided by size of matrix(if matrix are 20x3, Y or Z can be 2,4,5,10) code:
for k=0:100;
A(k*(2*Y)+(Y+1):k*(2*Y)+(2*Y),1:3)=A(k*(2*Y)+(2*Y):-1:k*(2*Y)+(Y+1),1:3);
end;
for j=0:100;
B(j*(2*Z)+(Z+1):j*(2*Z)+(2*Z),1:3)=B(j*(2*Z)+(2*Z):-1:j*(2*Z)+(Z+1),1:3);
end;
  댓글 수: 2
Dennis
Dennis 2018년 7월 6일
If Z is 10 and your matrix is 20x3, in your 2nd iteration you will try to index B(21,1) (1*2*10+10+1) - and even if your matrix is 2000x3 you might exceed your matrix dimensions in later iterations (100*2*10+10+1=2011).
Guillaume
Guillaume 2018년 7월 6일
Why all the extra brackets? In my opinion, it makes it more difficult to read.
A(2*k*Y+Y+1 : 2*k*Y+2*Y, 1:3) = A(2*k*Y+2*Y : -1 : 2*k*Y+Y+1, 1:3);

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2018년 7월 6일
I assume that k = 0:100 is a mistake. For your code to work k can't go higher than size(A, 1)/2*Y - 1.
It would appear that your code flip up down half of the rows of your matrices. That can be achieved simply without a loop:
A = reshape(A, 2*Y, [], size(A, 2));
A(Y+1:2*Y, :, :) = A(2*Y:-1:Y+1, :, :);
A = reshape(A, [], size(A, 3))

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by