Question about calling user defined function to another script

조회 수: 3 (최근 30일)
N/A
N/A 2022년 10월 27일
댓글: Stephen23 2022년 10월 27일
hello
first here is my user_defined_function code.(name is A_execute1.m)
function A=A_execute1(r)
global V;
A=pi*r*(sqrt(r^2+((9*V^2)/(pi^2*r^4))));
end
second, this is the script file(i made) that i want to call A_execute1 file to.
(to draw graph to see)
r=[-100:0.01:100];
V=10;
fminbnd('A_execute1',-100, 100)
plot(r,A_execute1(r)), xlabel('r'), ylabel('A')
grid
but it says error that
Error using fminbnd (line 237)
User supplied objective function must return a scalar
value.
Error in test4 (line 3)
fminbnd('A_execute1',-100, 100)
why it says that error?
i think i designed scalar value, not vector.

채택된 답변

Matt J
Matt J 2022년 10월 27일
편집: Matt J 2022년 10월 27일
It returns empty.
%r=[-100:0.01:100];
V=10;
A_execute1(-100)
ans = []
Don't use global variables. Use anonymous functions, or other alternatives discussed here.
[r,fval]=fminbnd(@(r) A_execute2(r,V),-100,100)
r = -99.9999
fval = -3.1416e+04
function A=A_execute1(r)
global V;
A=pi*r*(sqrt(r^2+((9*V^2)/(pi^2*r^4))));
end
function A=A_execute2(r,V)
A=pi*r*(sqrt(r^2+((9*V^2)/(pi^2*r^4))));
end
  댓글 수: 3
N/A
N/A 2022년 10월 27일
thx for your answer.
can i draw graph through anonymous function?
plot(@(r)), xlabel(''), ylabel('')
grid
or
plot(fun), xlabel(''), ylabel('')
grid
Matt J
Matt J 2022년 10월 27일
Yes, using fplot,
fun=@(r) r.^2;
fplot(fun, [-1,1])
or with,
r=linspace(-1,1);
plot(r,fun(r))

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by