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

1.216 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 18 de Oct. de 2021
Editada: MathWorks Support Team el 18 de Oct. de 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 comentarios
Rik
Rik el 9 de Abr. de 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 el 10 de Abr. de 2021
Editada: MathWorks Support Team el 4 de Mayo de 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

Iniciar sesión para comentar.

Más respuestas (1)

Gaganjyoti Baishya
Gaganjyoti Baishya el 21 de Jun. de 2020
Yeah it can be easily done. Instead of /* use %{
and instead of */ use %}
  1 comentario
Walter Roberson
Walter Roberson el 9 de Abr. de 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 .

Iniciar sesión para comentar.

Categorías

Más información sobre Modeling en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by