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

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"...
Adam Danz
Adam Danz 2022년 6월 20일
편집: Adam Danz 2022년 6월 21일
+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.
Thank you.
Passing input arguments is more efficient and more robust than using global variables:

댓글을 달려면 로그인하십시오.

답변 (1개)

Siraj
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.

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

제품

릴리스

R2022a

태그

질문:

2022년 6월 20일

답변:

2023년 8월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by