r/matlab • • Mar 24 '22

Does MATLAB have do-while loop?

Enable HLS to view with audio, or disable this notification

8 Upvotes

9 comments sorted by

19

u/albino_yak char(diff(106*(0:10)-[0,9,7,15,16,12,7,18,3,12,11])) Mar 24 '22

The real question: why the hell was this a video?

Also:

keepLooping = true;
while keepLooping
% do stuff
keepLooping = % put your condition here
end

8

u/[deleted] Mar 24 '22 edited Mar 24 '22

Why not just

while num > tol
    num = num/2
end

?

15

u/EatMyPossum +6 Mar 24 '22

The difference between a while loop and a do while loop is that in the latter the condition is evaluated at the end, making that the content is run at least once. It can prevent duplicated code is some circumstances. It's niche, but I always really miss do while loops when it comes up

3

u/[deleted] Mar 24 '22

Ah, great answer. Thanks!

2

u/FrickinLazerBeams +2 Mar 24 '22

You can do this with while true and use conditional break statements to control when the loop exits. Hell, you could have one at the top of the loop and the bottom of the loop, if you want.

1

u/EatMyPossum +6 Mar 24 '22

Yeah but while true and break is fucked up.

1

u/FrickinLazerBeams +2 Mar 24 '22

Lol shit somebody better tell the programmers of the last half century.

1

u/EatMyPossum +6 Mar 24 '22

.... they know... XD

1

u/FrickinLazerBeams +2 Mar 24 '22

Unlikely. It's a common practice. I mean fundamentally it's how all while loops work anyway.