Can this way of defining and using a global variable work?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2022-6-21
Passing input arguments is more efficient and more robust than using global variables:
回答(1 个)
Siraj
2023-8-31
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!