How can I reiterate a vector in side for loop when a condition is satisfied ?

조회 수: 1 (최근 30일)
I want to reiterate the angle when the condition is met, I tried to explain the question via the code below. I want re-iterate the value of the angle of the outer for loop (when the condition is met), in inner for loop in all the next iterations, in other words fix the value of angle that determined in the outer for loop and make it taking in consideration in the inner for loop in all next iterations.
Thanks in advance.
v=2;% velocity is 2 m/sec
for kk=1:100
for j=1:1 % OUTER LOOP
PreviousselectAngle_Max = selectAngle_Max(j)
angles= [21 25 36 80 90];
RandomizeOverAngles=randperm(numel(angles))
for i=1:1:5 % INNER LOOP
selectAngle = angles(RandomizeOverAngles(i))
displ(i,:) = [cos(selectAngle).v,sin(selectAngle).v]; % displacement
if Y % Condition is satisfied
displ = [cos(PreviousselectAngle_Max).v,sin(PreviousselectAngle_Max).v]; % Here I want in this loop
% only re-iterate PreviousselectAngle_Max in the all next
% iterations.
X(i) =do some calculations
end
end
[max,idx]=max(X)
selectAngle_Max(j) = angles(RandomizeOverAngles(j))
Y = condition % X is a condition
end
end

채택된 답변

Harsh Sanghai
Harsh Sanghai 2023년 3월 9일
Hi,
Based on your explanation, it seems like you want to fix the value of "PreviousselectAngle_Max" in the inner loop of the outer loop iterations where the condition is met. To achieve this, you can introduce a new variable "fixedAngle" that will store the value of "PreviousselectAngle_Max" when the condition is met. Then, you can use this "fixedAngle" variable to replace "PreviousselectAngle_Max" in the inner loop.
v = 2; % velocity is 2 m/sec
for kk = 1:100
for j = 1:1 % OUTER LOOP
PreviousselectAngle_Max = selectAngle_Max(j);
angles = [21 25 36 80 90];
RandomizeOverAngles = randperm(numel(angles));
fixedAngle = NaN; % initialize fixedAngle to NaN
for i = 1:1:5 % INNER LOOP
selectAngle = angles(RandomizeOverAngles(i));
if ~isnan(fixedAngle)
% use fixedAngle instead of PreviousselectAngle_Max
displ(i,:) = [cos(fixedAngle)*v, sin(fixedAngle)*v];
else
displ(i,:) = [cos(selectAngle)*v, sin(selectAngle)*v]; % displacement
end
if Y % Condition is satisfied
fixedAngle = PreviousselectAngle_Max; % fix the angle when condition is met
end
X(i) = do_some_calculations(displ(i,:));
end
[max, idx] = max(X);
selectAngle_Max(j) = angles(RandomizeOverAngles(j));
Y = condition; % Y is a condition variable
end
end
  댓글 수: 1
omar th
omar th 2023년 3월 9일
@Harsh Sanghai Thank you so much for your answer, you got my point and your answer is sufficient, thanks again

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by