Simulink stuck on while loop with Time condition
4 views (last 30 days)
Show older comments
Shehryaar Ali
on 13 Feb 2022
Answered: Image Analyst
on 13 Feb 2022
I want to implement a while loop inside a MATLAB Function in Simulink, whose condition is dependant on time and would not change otherwise. But when I try to run the simulation, it shows "Running" but does not progress beyond that. My real function is rather complex, but here is an example of what I wanted to do:
function [Discharge,Charge] = Decode(Matrix,Time)
mat = Matrix(Matrix~=0);
mat = reshape(mat,numel(mat)/3,3);
Discharge = zeros;
Charge = zeros;
while Time <= 60
Discharge = mat(i,1);
Charge = mat(i,2);
end
end
0 Comments
Accepted Answer
Image Analyst
on 13 Feb 2022
Look at your while loop. If it gets in there, how does it ever leave? Time does not change in the loop so if Time is less than 60 it will get stuck in an infiinte loop. Another problem with it : since "i" never changed, the Discharge and Charge value will never change. Third problem : there is no failsafe - a way to quit the loop if you exceed some number of iterations that you believe should never be reached. Possible fix:
maxIterations = 1000;
[rows, columns] = size(mat);
loopCounter = 1;
startTime = tic;
elapsedSeconds = toc(startTime);
while (elapsedSeconds <= 60) && loopCounter < maxIterations
Discharge = mat(loopCounter, 1);
Charge = mat(loopCounter, 2);
loopCounter = loopCounter + 1;
elapsedSeconds = toc(startTime);
end
You might also want to do some checks on Charge and Discharge since those are the things that are changing in the loop.
0 Comments
More Answers (0)
See Also
Categories
Find more on Simscape Electrical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!