Clear Filters
Clear Filters

Using a function to pass variables to another .m File (GUI)

2 views (last 30 days)
I wanted to pass a value obtained in my File1.m to File2.m using functions. I tried using global vairables but it started get messy
Example:
% In File1
I = snapshot(cam)
% In File2
rgb2gray(I)
How would use function to transfer this to file2.m.
Thank you for your help

Answers (1)

DGM
DGM on 23 Mar 2021
Edited: DGM on 23 Mar 2021
This is the background material:
Say File1.m is something like you showed, and you're expecting the processed image to be returned by File2:
I=snapshot(camera);
graypict=File2(I);
and then File2.m would look something like this:
function outpict=File2(inpict)
outpict=rgb2gray(inpict);
end
Though maybe you'd want to choose a better function name than "File2", and maybe you want it to do more than one thing. Let's say it needs to be flipped too:
function outpict=grayimageflipper(inpict)
outpict=flip(rgb2gray(inpict),2);
end
... which would be called like:
flippedpicture=grayimageflipper(I);
and so on. In both examples, the first non-commented line in File2 is a function definition that describes three basic things:
  • The output argument(s)
  • The function name
  • The input argument(s)
There can be multiple input and output arguments specified, and the number of arguments can be variable. It all depends what you want to do.
  2 Comments
Jesvin Jose
Jesvin Jose on 23 Mar 2021
Thank you for your response Im getting an error, I am using GUI therefore I cannot use "end" to terminate the function. Furthermore, would you mind explaining "inpict" where did that variable come from?
Thank you for your time :)
DGM
DGM on 23 Mar 2021
inpict is just what I chose to call the input argument. Since you're passing I as the argument in the call to File2, and the function definition says the first (and only) input argument is called inpict, then inpict is a copy of I that exists only within the scope of File2.
Similarly, the function definition in File2 describes the output argument as outpict. Outpict is the array that becomes graypict. I'm probably doing a terrible job of describing this.
Unless you're nesting functions, you usually don't need the end statement. I find it's easier to read with them, so I use them. If you add an end statement to any one function in a file, then all the functions do need an end statement, otherwise the scoping becomes ambiguous.

Sign in to comment.

Categories

Find more on Images 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!