How can I evaluate a function in a script in MATLAB?

조회 수: 1 (최근 30일)
Xingyi Dai
Xingyi Dai 2016년 7월 31일
댓글: Walter Roberson 2016년 7월 31일
I am trying to write a function as a script file. And then put the variables in the function to get output as an array.
That's I am able to do:
function try
a = [-2 1 7.5];
ans = myfunction(a)
function y = myfunction(x)
y = 1/(x^2 + 1)
end
However, it shows solution not found. I know how to call the function on the command window but on idea how to make it done all in the script file.
Thanks in advance. Bonnie
  댓글 수: 1
Stephen23
Stephen23 2016년 7월 31일
편집: Stephen23 2016년 7월 31일
Do not use try or ans as variable / function names, as these are both names of important inbuilt functions. For the same reason you should never use size, cell, length, i, j, etc, etc.
You can use which to check if a name is already used.

댓글을 달려면 로그인하십시오.

답변 (1개)

Image Analyst
Image Analyst 2016년 7월 31일
편집: Image Analyst 2016년 7월 31일
Bonnie, because myfunction ended with an "end", try must also end with an "end". Ends are optional (I don't use them) but if one function in an m files uses it then all function need to use ends.
Also you need to use ./ instead of /, and .^ instead of ^ in your formula since x is an array. Corrected trythis.m is below:
function trythis
a = [-2, 1, 7.5];
answer = myfunction(a)
end
function y = myfunction(x)
y = 1 ./ (x .^ 2 + 1)
end
  댓글 수: 2
Xingyi Dai
Xingyi Dai 2016년 7월 31일
Thank you but still shows solution not found:(
Walter Roberson
Walter Roberson 2016년 7월 31일
Works for me. Store those two functions in trythis.m and then at the command line command
trythis

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Import and Analysis에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by