How can I save functions or sub functions in matlab?

35 vues (au cours des 30 derniers jours)
methaq ali
methaq ali le 23 Août 2018
Modifié(e) : Stephen23 le 23 Août 2018
Dear all, I know how to save variables, but how can I save functions or sub functions in matlab? Thanks..
  2 commentaires
Stephen23
Stephen23 le 23 Août 2018
Modifié(e) : Stephen23 le 23 Août 2018
How are you trying to define this function?
methaq ali
methaq ali le 23 Août 2018
Modifié(e) : Stephen23 le 23 Août 2018
Dear Stephen, I make copy for this code:
function [m,s] = stat(x)
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
end
% Call the function from the command line.
values = [12.7, 45.4, 98.9, 26.6, 53.1];
[ave,stdev] = stat(values)
Directly from Matlab help to my matlab R2014a editor I get this message in command win.:
function [m,s] = stat(x)
|
Error: Function definitions are not permitted in this context.
Thanks..

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 23 Août 2018
Modifié(e) : Stephen23 le 23 Août 2018
It is not clear from your explanation where you are defining the function, but I can see two main possibilities which would generate that error (or a similar error):
  • Trying to define a function in the command window: this is not allowed in MATLAB, all functions must be saved in a file (except for anonymous functions).
  • Trying to define a function inside a script: only MATLAB versions from R2016B+ support functions defined in scripts. You need to read the documentation carefully for your version, not the online help (which is for the most recent version): for your MATLAB version it is not possible to define a function inside a script.
In practice if you want to define a function then do NOT have any code outside of any function declaration, e.g. this needs to be the entire file contents:
function [m,s] = stat(x)
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
end
You can add local functions to the same file, but NO CODE outside of those functions. Save the function as a file stat.m (you should use the same name as the function itself). Then it will work.

Plus de réponses (1)

KSSV
KSSV le 23 Août 2018
function c = mysum(a,b)
c = a+b ;
end
The above is a function.....as I have named it mysum, when you try to save, it will be automatically saved on the name mysum.m.
  3 commentaires
methaq ali
methaq ali le 23 Août 2018
Thank you for answering my quastion but when copy this code to matlab the following error massage appear: function c = mysum(a,b ) | Error: Function definitions are not permitted in this context. I dont Know why!
Dennis
Dennis le 23 Août 2018
Try to create a script (top left -> New Script).

Connectez-vous pour commenter.

Catégories

En savoir plus sur Scope Variables and Generate Names dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by