How to save data into an array from a for loop

조회 수: 2 (최근 30일)
Lucie Jackson
Lucie Jackson 2021년 12월 9일
댓글: Star Strider 2021년 12월 9일
This is my code, I need it to run through theta from 1 to 360 degrees, and also run through different values of op for every value of theta. I believe this code does that but I don't know how to save the data from the for loop. Thank you in advance for any advice!
for theta = 1:360
for op = -400:0.5:400
A = [cosd(theta) sind(theta) 0; -sind(theta) cosd(theta) 0; 0 0 1];
Rotstress = A*stress*A.';
oynew = Rotstress(2,2)+op*sind(theta);
oxnew = (Rotstress(1,1))+op*cos(theta);
end
end

답변 (1개)

Star Strider
Star Strider 2021년 12월 9일
It is not possible to use ‘op’ as an index, so it needs to be restated to use it in that context. The ‘theta’ vector can be used as an index without modification here.
opv = -400:0.5:400;
for theta = 1:360
for k = 1:numel(opv)
op = opv(k);
A = [cosd(theta) sind(theta) 0; -sind(theta) cosd(theta) 0; 0 0 1];
Rotstress = A*stress*A.';
oynew(theta,k) = Rotstress(2,2)+op*sind(theta);
oxnew(theta,k) = (Rotstress(1,1))+op*cos(theta);
end
end
I assume the goal is to save ‘oynew’ and ‘oxnew’ so I subscripted them here.
.
  댓글 수: 2
Lucie Jackson
Lucie Jackson 2021년 12월 9일
Thank you! I've actually just realised I made a slight mistake in the code I copied, would it be possible to run it from 0:360 degrees? (when I try this it throws errors as I assume it is not an integer position in the array it is being recorded in)
Star Strider
Star Strider 2021년 12월 9일
No, MATLAB indexing begins at 1, so the code would have to be —
opv = -400:0.5:400;
thetav = 0:360;
for k1 = 1:numel(thetav)
theta = thetav(k1);
for k2 = 1:numel(opv)
op = opv(k);
A = [cosd(theta) sind(theta) 0; -sind(theta) cosd(theta) 0; 0 0 1];
Rotstress = A*stress*A.';
oynew(k1,k2) = Rotstress(2,2)+op*sind(theta);
oxnew(k1,k2) = (Rotstress(1,1))+op*cos(theta);
end
end
.

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by