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

1 vue (au cours des 30 derniers jours)
kat001
kat001 le 21 Juin 2018
Commenté : Rena Berman le 27 Juil 2018
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 commentaires
kat001
kat001 le 21 Juin 2018
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 le 27 Juil 2018
(Answers Dev) Restored edit

Connectez-vous pour commenter.

Réponses (1)

umichguy84
umichguy84 le 5 Juil 2018
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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by