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

조회 수: 5 (최근 30일)
alpedhuez
alpedhuez 2022년 6월 20일
답변: Siraj 2023년 8월 31일
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
Stephen23 2022년 6월 21일
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.

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by