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

3 ビュー (過去 30 日間)
Jesvin Jose
Jesvin Jose 2021 年 3 月 23 日
コメント済み: DGM 2021 年 3 月 23 日
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

回答 (1 件)

DGM
DGM 2021 年 3 月 23 日
編集済み: DGM 2021 年 3 月 23 日
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 件のコメント
Jesvin Jose
Jesvin Jose 2021 年 3 月 23 日
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 2021 年 3 月 23 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeImages についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by