Can I comment a block of lines in an MATLAB file using /* ... */ as I can in C?

1,120 views (last 30 days)
I understand that in MATLAB we can comment line by line using % but this is troublesome, especially if I have a whole group of lines that I want to comment out temporarily. Is there anyway we can 'block' comment, like in 'C' where we can use /* at the beginning of a block of comments and */ at the the end of the block?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 18 Oct 2021
Edited: MathWorks Support Team on 18 Oct 2021
You can comment out a block of code in MATLAB using the block comment operators, %{ and %}.  The %{ and %} operators must appear alone on the lines that immediately precede and follow the block of code that you want to comment out. Do not include any other text on these lines.
For example: 
a = magic(3); 
%{ 
sum(a) 
diag(a) 
sum(diag(a)) 
%}
sum(diag(fliplr(a))) 
You also can comment out a block of code by selecting the code, going to the Editor or Live Editor tab, and pressing the comment button:
 Alternatively, you can type Ctrl+R.
To uncomment the selected lines code, press the uncomment button: 
Alternatively, you can type Ctrl+Shift+R.
For more information about adding comments to code, see: 
  5 Comments
Rik
Rik on 9 Apr 2021
(working from memory):
I believe adding whitespace is fine as well, but I haven't checked if that only allows space, or if other whitespace characters are also allowed. One of the many exceptions I needed to handle to strip comments from code.
Walter Roberson
Walter Roberson on 10 Apr 2021
Edited: MathWorks Support Team on 4 May 2023
Testing only single characters immediately after the %{ the ones that do not interrupt the meaning as comment are:
  • 9 (tab)
  • 10 (newline)
  • 11 (vertical tab)
  • 12 (form feed)
  • 13 (carriage return)
  • 32 (space)
This excludes a number of Unicode spacing characters such as No-Break Space and Zero-Width No-Break Space; https://jkorpela.fi/chars/spaces.html

Sign in to comment.

More Answers (1)

Gaganjyoti Baishya
Gaganjyoti Baishya on 21 Jun 2020
Yeah it can be easily done. Instead of /* use %{
and instead of */ use %}
  1 Comment
Walter Roberson
Walter Roberson on 9 Apr 2021
C and C++ permit /* */ to appear in the middle of a line and the rest of the line after the */ will be executed for them. MATLAB requires that %{ and %} be on lines by tthemselves .

Sign in to comment.

Categories

Find more on Introduction to Installation and Licensing 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!