can we run codes from 2nd line onwards?

1 Ansicht (letzte 30 Tage)
Megha
Megha am 9 Feb. 2021
Kommentiert: Rik am 9 Feb. 2021
I am running my codes externally i.e. calling one *.m file from another using "run(filename)" command.
Can I call this run(filename) from 2nd line onwards or can i skip few lines?
As first line contains clear command, it clears all the previous variables.
  1 Kommentar
Stephen23
Stephen23 am 9 Feb. 2021
"As first line contains clear command, it clears all the previous variables."
A much better solution would be to write functions instead of scripts.
And avoid programmatic use of clear, which is massively overused by beginners and yet rarely required.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 9 Feb. 2021
Not exactly. You cannot tell MATLAB to skip the first line of a file during run(). However, you can read the content of the file, remove the first line, and execute that content.
temporary_string = fileread(filename);
temporary_string = regexprep(temporary_string, '^[^\n]*\n', ''); %delete first line
eval(temporary_string)
Strictly speaking, this is not equivalent to run(), in that run cd's to the directory the file is in but this code does not do that. That makes a difference in search paths -- for example if there was a private/ directory in the folder the file is stored in, then run() would use the functions in the private/ folder, but the above code will not.
  2 Kommentare
KALYAN ACHARJYA
KALYAN ACHARJYA am 9 Feb. 2021
@Walter Roberson Sir i misunderstood the question, thanks for clarification!
Rik
Rik am 9 Feb. 2021
Just a note: as the default encoding for .m files is now UTF-8, using fileread might result in incorrect values of strings/chars.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Adding custom doc finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by