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

1.209 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

MathWorks Support Team
MathWorks Support Team il 18 Ott 2021
Modificato: MathWorks Support Team il 18 Ott 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 Commenti
Rik
Rik il 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 il 10 Apr 2021
Modificato: MathWorks Support Team il 4 Mag 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

Accedi per commentare.

Più risposte (1)

Gaganjyoti Baishya
Gaganjyoti Baishya il 21 Giu 2020
Yeah it can be easily done. Instead of /* use %{
and instead of */ use %}
  1 Commento
Walter Roberson
Walter Roberson il 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 .

Accedi per commentare.

Categorie

Scopri di più su Modeling in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by