how to break out of a for and while loop in this particular problem?
1 次查看(过去 30 天)
显示 更早的评论
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');
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/191404/image.jpeg)
3 个评论
回答(1 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!