Getting variables from a custom function with a GUI
Show older comments
I've written a function that creates a GUI requesting the user to input two dates (start and stop). I've included format checking to ensure the user has inputted things correctly.
The part I am missing is how to assign the variables in a way to allows the inputs to be accessible outside the function (i.e. when calling the function with a different script).
Any advice would be appreciated. I can repost sharing the code if that would help.
3 Comments
Charlie Wood
on 10 Jan 2024
Note that DATESTR is deprecated, will be removed in the future, and is NOT recommended.
Replace:
datestr(datetime('today'), 'dd mmm yyyy HH:MM:SS.FFF')
with e.g.:
string(datetime('today', 'Format','dd MMM yyyy HH:mm:ss.SSS'))
Charlie Wood
on 10 Jan 2024
Accepted Answer
More Answers (1)
Hello Charlie,
There are a couple of methods to accsess variables outside of their local function workspace.
The most straightforward is to simply define them as an output variable for the function
%% Script that calls the function handling the user input
[StartDate,StopDate] = FunctionThatGetsUserInputThroughGUI(SomeInput)
%StartDate and StopDate is now available in the workspace that called the
%function.
%Assume you have some function to handle the variables
%Define the output variables as [output1, output2,..., outputN]
function [StartDate, StopDate] = FunctionThatGetsUserInputThroughGUI(SomeInput)
% your code here that creates GUI resulting in the start and stopdate e.g.
StartDate = datetime('yesterday');
StopDate = datetime('today');
end
Less reccommended options would be to use assignin...
%% Script that calls the function handling the user input
FunctionWithAssignin(SomeInput)
%StartDate and StopDate is now available in the workspace that called the
%function.
function FunctionWithAssignin(SomeInput)
% your code here that creates GUI resulting in the start and stopdate e.g.
StartDate = datetime('yesterday');
StopDate = datetime('today');
assignin('caller','StartDate',StartDate)
assignin('caller','StartDate',StartDate)
end
... or global variables
%% Script that calls the function handling the user input
global StartDate StopDate
FunctionWithGlobals(SomeInput)
%StartDate and StopDate is now available in the workspace that called the
%function.
function FunctionWithGlobals(SomeInput)
global StartDate StopDate
% your code here that creates GUI resulting in the start and stopdate e.g.
StartDate = datetime('yesterday');
StopDate = datetime('today');
end
Good Luck!
Categories
Find more on App Building in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!