execute a statement from one .m file into another .m file by specifying line number.

3 views (last 30 days)
Guys , I have two .m files. I wish to execute certain part of code from my first file in my second file.Is there a way I can do it by specifying in second file, to execute certain statements of the first file by mentioning the line numbers at which my statement is written in first file?

Answers (1)

Jan
Jan on 8 Mar 2015
No. And this would be a really ugly way of programming. It would be a GOTO command, and we are so lucky that Matlab offers a celan and structured way to avoid such methods.
Simply insert the needed code section by copy&paste or move it to a dedicated function.
  1 Comment
Ken Atwell
Ken Atwell on 8 Mar 2015
To expound on this: Let's say you have the file first.m and second.m. Rather than try to find a way to call a subset of second.m (which MATLAB doesn't -- and shouldn't -- allow), do the following:
  1. Move of the code of interest into a new file, third.m
  2. Have first.m call third.m
  3. Have second.m also call third.m
You might be able to get away with keeping all three files as simple scripts (that is, MATLAB files that don't begin with a function statement), but at some point you will want to learn about functions as a better way of reusing code. Read Scripts vs. Functions when you have a moment.

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!