필터 지우기
필터 지우기

can we run codes from 2nd line onwards?

조회 수: 3 (최근 30일)
Megha
Megha 2021년 2월 9일
댓글: Rik 2021년 2월 9일
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
Stephen23
Stephen23 2021년 2월 9일
"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.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2021년 2월 9일
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
KALYAN ACHARJYA
KALYAN ACHARJYA 2021년 2월 9일
@Walter Roberson Sir i misunderstood the question, thanks for clarification!
Rik
Rik 2021년 2월 9일
Just a note: as the default encoding for .m files is now UTF-8, using fileread might result in incorrect values of strings/chars.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by