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!