function for m file
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I was given the function:
g(x,y) = (x^2/y^4)+(cos(7*x*exp(9*y))/(x^6 + 2));
and was instructed to format it as an anonymous function:
g = @(x,y) (x^2/y^4)+(cos(7*x*exp(9*y))/(x^6 + 2));
When trying to create the m file, the contents were written as:
g = @(x,y) (x^2/y^4)+(cos(7*x*exp(9*y))/(x^6 + 2
function g = f(x,y)
g = (x^2/y^4)+(cos(7*x*exp(9*y))/(x^6 + 2));
end
When then trying to run the file, this error appears:
Error: File: g.m Line: 1 Column: 1
Using 'g' as both the name of a variable and the name of a script is not supported.
The file is to be named g.m and be called using g(x,y), x and y being any number, as per assignment instructions. What is causing the file not to run?
1 commentaire
Stephen23
le 7 Sep 2024
Modifié(e) : Stephen23
le 7 Sep 2024
"What is causing the file not to run?"
The error message already tells you exactly what the problem is. Lets read it:
"Using 'g' as both the name of a variable and the name of a script is not supported."
Lets look at the information you gave about the script name:
"The file is to be named g.m ..."
Lets look at the information you gave about the variable name:
function g = f(..)
g = (..);
end
So you clearly used g for both the filename as well as the name of a variable. Which the error message clearly states is not allowed. If the error message unclear, how could it be improved?
Réponse acceptée
Piyush Kumar
le 7 Sep 2024
@Hunter, The error you are getting is due the same name of variable and script.
Here’s how you can resolve this issue:
1. Anonymous Function: If you want to use an anonymous function, you don’t need to create a separate file. You can define it directly in the command window or in a script:
g = @(x,y) (x^2/y^4) + (cos(7*x*exp(9*y))/(x^6 + 2));
% g(2, 3)
2. Function File: If you need to create a function file, ensure the file name matches the function name and avoid using the same name for variables.
% Do not add anonymous function
function result = g(x, y)
result = (x^2/y^4) + (cos(7*x*exp(9*y))/(x^6 + 2));
end
% Save the file as g.m and call like -- " result = g(2, 3); disp(result);
To summarize, if you need to call the function using g(x, y), you should use the second approach and ensure your file is named g.m.
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Whos 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!