Use of semicolon in a for loop
21 views (last 30 days)
Show older comments
Hello,
I think I once read somewhere that using a semicolon in a for loop statement i.e.
for i = 1:N; %With a semicolon
my_function
end
instead of
for i = 1:N %No semicolon
my_function
end
was better because the 1:N was not created. However I can't seem to be able to find anything about it anymore. Could someone tell if it's true or not or if not what's the point of using a semicolon?
0 Comments
Accepted Answer
Walter Roberson
on 19 Dec 2011
"for" does not create the list 1:N in any modern MATLAB (I do not know if it ever did.)
Some people put in semi-colons out of habit, or because they do not realize that they are not needed. Or they might originally have written
for i = 1:N; my_function; end
and reformatted later and forgot to remove the semi-colon.
I do not know if there is any execution or parsing time difference for using the semi-colon. Some MATLAB versions have had timing oddities so I would not rule out the possibility.
More Answers (1)
Daniel Shub
on 19 Dec 2011
I don't think a semicolon or comma adds anything. It does allow everything to be written on one line like
for i = 1:N; my_function, end
Outside of the command window, I am not sure why you would want to do this.
4 Comments
Daniel Shub
on 19 Dec 2011
No, you don't need it, but sometimes it is easier. I find tab completion and the history behaves better if it is all on one line.
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!