필터 지우기
필터 지우기

Saving all output of for loop

조회 수: 1 (최근 30일)
Tchilabalo
Tchilabalo 2019년 5월 12일
댓글: madhan ravi 2019년 5월 16일
for i=1:1500
X1=J(i)-sqrt((D(i)^2)/((sqrt(A(i))+1)))
Y1=I(i)-A(i)*(J(i)-X1)
X2=J(i)+sqrt((D(i)^2)/((sqrt(A(i))+1)))
Y2=I(i)+A(i)*(X2-J(i))
end
coord=[X1(:),Y1(:),X2(:),Y2(:)]
%coord
writematrix(coord,'Coord_15.csv')
I am trying to save the coordinates (X1, X2, Y1,Y2) from a for loop as shown in the code above. All inputs (I, J, A, D) are columns vectors , but i only the last iteration is saved. I will appreciate any help.

채택된 답변

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019년 5월 12일
Hi,
Simply add (i) after your output variables, viz. X1, Y1, X2, Y2:
for i=1:1500
X1(i)=J(i)-sqrt((D(i)^2)/((sqrt(A(i))+1)))
Y1(i)=I(i)-A(i)*(J(i)-X1)
X2(i)=J(i)+sqrt((D(i)^2)/((sqrt(A(i))+1)))
Y2(i)=I(i)+A(i)*(X2-J(i))
end
coord=[X1(:),Y1(:),X2(:),Y2(:)]
%coord
writematrix(coord,'Coord_15.csv')
Good luck
  댓글 수: 4
madhan ravi
madhan ravi 2019년 5월 16일
편집: madhan ravi 2019년 5월 16일
Then why did you accept the answer if it doesn’t solve the problem??
Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019년 5월 16일
Before commenting any point verify what you have stated. That is the correct answer. Vectorization is another solution.

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

추가 답변 (1개)

madhan ravi
madhan ravi 2019년 5월 12일
편집: madhan ravi 2019년 5월 16일
You don't need a loop , this is straight forward just vectorize your code:
Note: The other answer doesn‘t show the importance of preallocation.
X1=J-sqrt((D.^2)./((sqrt(A)+1)));
Y1=I-A.*(J-X1);
X2=J+sqrt((D.^2)./((sqrt(A)+1)));
Y2=I+A.*(X2-J);
coord=[X1(:),Y1(:),X2(:),Y2(:)];
writematrix(coord,'Coord_15.csv')
  댓글 수: 2
Stephen23
Stephen23 2019년 5월 16일
+1 simple and efficient
madhan ravi
madhan ravi 2019년 5월 16일
Thank you Stephen.

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

카테고리

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