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

6 visualizzazioni (ultimi 30 giorni)
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 Commenti

Accedi per commentare.

Risposte (1)

Siraj
Siraj il 31 Ago 2023
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.

Categorie

Scopri di più su Environment and Settings in Help Center e File Exchange

Tag

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by