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

1 回表示 (過去 30 日間)
omar th
omar th 2023 年 3 月 9 日
コメント済み: omar th 2023 年 3 月 9 日
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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by