how to break out of a for and while loop in this particular problem?

1 回表示 (過去 30 日間)
kat001
kat001 2018 年 6 月 21 日
コメント済み: Rena Berman 2018 年 7 月 27 日
Hi,
So this is how the outcome looks like. The simulation is running from t = 0 to t = 20. The maximum power is already at t = 12. the algorithm is built in such a way that the movement of position will keep the max. power at aprrox. 1. However, I would like to let the simulation run till t=16 and then break out of the for-loop as well as while-loop to call another function. I don't want to change the 't' value. I have the code attached here. The "while-section" of the code is something that is not correct och need to be fixed according to the description above. Any idea?
Maybe, there is another way to fix this. How about checking whether the power is not varying too much and then break the loop? Is there a way to write that code? This would be the most preferable.
format long g;
format compact;
fontSize = 20;
Dummy Power
NoisePowerX = 0.1;
x = -5:0.1:5;
norm = normpdf(x,0,0.3925);
%%Assigning Varaibles & Vectors
set_t_end = 20;
t = 0:1:set_t_end; %time
xi = 1; % initial position of x
xPos = zeros(1, length(t)); % creates 100 columns containing zeros
normT = zeros(1, length(t));
%initial movement
xPos(1)=xi;
normT(1) = norm(find(abs(x-xi)<min(diff(x))/2));
xi=xi+0.1;
xPos(2)=xi;
normT(2) = norm(find(abs(x-xi)<min(diff(x))/2));
%%I believe this section needs to be corrected for the given problem.
for k = 3:length(t)
while 1
if (normT(k-1) > normT(k-2))
xi = xi + (xPos(k-1) - xPos(k-2));
else
xi = xi - (xPos(k-1) - xPos(k-2));
end
xPos(k) = xi; % saving increment/decrement of position in xPos for each step
normT(k) = norm(find(abs(x-xi)<min(diff(x))/2));
break;
end
end
plot(t, xPos, 'r-', 'LineWidth', 2);
ylabel('X Position', 'FontSize', fontSize);
hold on;
plot(t, normT, 'b-', 'LineWidth', 2);
grid on
hold off
ylabel('Power', 'FontSize', fontSize);
title('Peak Power', 'FontSize', fontSize);
xlabel('t', 'FontSize', fontSize);
legend('xPos', 'Pwr', 'Location', 'east');
  3 件のコメント
kat001
kat001 2018 年 6 月 21 日
Correct. However, the issues isn't there. The issue is how to break out at t=16. Currently, its running all the way to t=20.
Rena Berman
Rena Berman 2018 年 7 月 27 日
(Answers Dev) Restored edit

サインインしてコメントする。

回答 (1 件)

umichguy84
umichguy84 2018 年 7 月 5 日
If you want to break out at t = 16 why not just run your for loop to 16?
for k = 3:length(16)
xPos(k) = ...;
end
% Alternatively
k = 3;
while t(k) < 16
xPos(k) = ...;
k = k + 1
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by