MATLAB Answers

How can I pass a variable between a m-file and another m-file that runs a gui?

16 views (last 30 days)
Ricardo Duarte
Ricardo Duarte on 22 Sep 2020 at 21:57
Commented: Ricardo Duarte on 25 Sep 2020 at 11:15
I'm trying to pass a variable between one m-file and another m-file that initiates gui.
More specifically:
I have one m-file (mfile1) that is concerned with the initiation of gui, however, some calculations are made in other m-file(mfile2).
I would like to pass some variables in the mfile2 to the mfile1.
Is it possible?
Thank you in advance.


Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 22 Sep 2020 at 23:19
Edited: Adam Danz on 23 Sep 2020 at 11:29
M files can contain scripts or functions but variables can only be passed to functions so the m-file must be written as a function [see Scripts vs Functions and Create Function in Files].
For example,
function [output] = mfile2(input)
% add 1 to the input and pass the result to mfile2.
y = input + 1;
% Send y to mfile1 and get the result
% mfile1 divides y by 2 to z equals (input+1)/2
z = mfile1(y);
function [output] = mfile1(input)
% divide the input by two
output = input/2;
All variables needed in a function must either be passed into the function as inputs or defined within the function. If your functions interact with your GUI, pass the handle structure into the function.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!