Can this way of defining and using a global variable work?

I have main.mlx, plot1.m, and plot2.m. plot1.m and plot2.m is called from main.mlx, get data from 'main.mlx, create plots, and save plots. I want to define a folder that these plots will be saved.
I think of using a global variable to define the folder.
I say, at main.mlx
global folder
folder = 'C:';
Then I say, at plot1.m,
filename=fullfile(folder, 'plot1.jpg')
exportgraphics(t,filename)
Will this work?

4 Comments

Not without the companion global declaration, no.
While it can be made to work, it would be much cleaner design to simply pass the directory and file names a arguments.
It would also be better to not clutter the root directory itself with "stuff"...
+1 for @dpb's advice to avoid this.
Another approach would be to change your current folder (cd) and then you just need to specify the filename unless your code makes additional changes to the current directory. However, I much prefer passing the path to the m files as dpb suggested.
Passing input arguments is more efficient and more robust than using global variables:

Sign in to comment.

Answers (1)

Hii! It is my understanding that you want to share the destination folder for the plots from your “main.mlx” script to function files “plot1.m” and “plot2.m”.
One of the possible ways to do this is to use a global variable, but it has some risks associated with it because any function can access and update a global variable. Other functions that use the variable might return unexpected results.
Therefore, the best practice is to pass this information as an argument to the “plot1” and “plot2” functions.
Refer to the code below for further understanding.
Sample code for “plot1.m”.
function plot1(xdata, ydata, folder)
filename=fullfile(folder, 'plot1.jpg');
figure, plot(xdata,ydata);
f = gcf;
exportgraphics(f,filename);
end
Sample code for “plot2.m”
function plot2(xdata, ydata, folder)
filename=fullfile(folder, 'plot2.jpg');
figure, plot(xdata,ydata);
f = gcf;
exportgraphics(f,filename);
end
Sample code for “main.mlx
folder = 'testplots'; %relative path of the folder with respect to the current working directory.
if ~exist("testplots", "dir") % if the folder does not exist create it.
mkdir("testplots");
end
x = [1,2,3];
y = [1,2,3];
plot1(x,y,folder)
plot2(x,y,folder)
For a better understanding of different ways to share data between workspaces refer to the following documentation. https://in.mathworks.com/help/matlab/matlab_prog/share-data-between-workspaces.html
Hope this helps.

Categories

Find more on Programming in Help Center and File Exchange

Products

Release

R2022a

Tags

Asked:

on 20 Jun 2022

Answered:

on 31 Aug 2023

Community Treasure Hunt

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

Start Hunting!