function for m file
8 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2024-9-7
编辑:Stephen23
2024-9-7
"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?
采纳的回答
Piyush Kumar
2024-9-7
@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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!