Why all the code in a MATLAB program are just functions
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
I have a downloaded code which is all functions, and when I run it it (F5) it works.
The code is a GUI which execute image analysis functions.
When I contract all the function drop-downs (with Ctrl + "," ), all the code is based in funtions, there is no one no-function code, and it run correctly anyway when I execute it.
I don't understand that all the code runs without any no-function code, which in my understanding it would be the necessary for to run the functions and the code.
Thank you very much.
Josep
2 commentaires
Rik
le 6 Juil 2021
When you run the function with F5 it will run the first function in the file (technically there are exceptions, but let's not focus on those now).
Apparently that creates a figure with some interactive elements. When you interact with such elements, those will have callback functions. That means that you are actually calling one of those internal functions when you click on a button.
It therefore makes perfect sense that there are only functions: you ran the function that created the figure and the elements, and interacting with an element will call a specific function.
Did you do a basic Matlab tutorial? Do you have a specific question?
Réponse acceptée
Jan
le 6 Juil 2021
"No function code" is code written to a "script". Scripts share their workspace (the list of loclly used variables) with their caller. This has some sever disadvantages and professional code avoid scripts, but use functions with exactly defined inputs and outputs.
If a script does not use variables defined or used anywhere else, it can be converted to a function easily:
% This is my script file called "hello.m":
disp('hello')
To:
function hello
% This is my hello function stored in the file "hello.m":
disp('hello')
end
Both codes are equivalent and if you start them by F5 (green triangle) both do exactly the same.
"without any no-function code" is the standard case. Only tiny hacks or experimental code of beginners can be stored in scripts (an some very specific exceptions, where scripts are really the best choice).
Plus de réponses (0)
Voir également
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!