How to call .m file from an other .m file?

24 visualizaciones (últimos 30 días)
Zeynab Mousavikhamene
Zeynab Mousavikhamene el 3 de Sept. de 2019
Respondida: Rik el 3 de Sept. de 2019
I have a matlab file which is reading a .json file and do some calculations on it and produces some parameters with their values, tables and plots. I have multiple .json files with excatly the same structure but different numbers. They are iterations of a simulation. I want to write a matlab .m file that can call the main .m file and repeat all those steps for each individual .json file. I want to calculate the averages of all those calculations and produce the same parameters and their values and plots with variances.
Let's assume the file that reads .json file and does calculations is main.m. The second .m file that calls the main.m is second.m.
Here are my questions:
  1. How can I call a main.m file (it is not a fucntion) from an other second.m file in repeated way? I mean call main.m file in a loop like do this on all the .json files?
  2. How can I automatically ask the second.m file to extract data parameters and tables from main.m and produce parameters' means and variances without changing the main.m file. The basis of calculation and plot extraction would be on main.m file but I want to do averaging and calculating variance to be in the second.m file.
Thanks for helps in advance

Respuestas (2)

Jim Riggs
Jim Riggs el 3 de Sept. de 2019
Editada: Jim Riggs el 3 de Sept. de 2019
Use the command
run(filename)
Any variables defined in the script are available in the Matlab workspace.

Rik
Rik el 3 de Sept. de 2019
Scripts should only be used for examples and debugging. Your code is a function, so you shouldn't treat it as a script. It would probably even make more sense to split your code into several functions.
Function are great. They make it trivial to only change a single parameter like a file name for multiple runs, they make your code predictable, and they make your code reusable. That last one is especially important. I only want to debug a function once. Once it works for the input types I describe, I never need to look at the function again. Why spend your time on solving problems you have already solved?
The main thing is to find a balance: your functions should be small enough that they do something generally useful, but not so small that you need more than 20 to do something useful.
If you are not allowed to change main.m, you should consider encapsulating it in a function that calls it with run (or just by putting main in your code), and then providing the variables as outputs.

Community Treasure Hunt

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

Start Hunting!

Translated by