Same code, different result????

1 次查看(过去 30 天)
I made a code calculating a numerical integration of a function as the professor taught, but it made an error and couldn't get answer
but when the TA tried it with my code, just copying and pasting, she got a corect answer, while I could not:(
What's the problem
Below is my code:
clc
function f_int=trapezoid(ta,tb,n)
format long
dt=(tb-ta)/n; t=ta;
sum=0.;
sum=func(t);
for i=1:n-1
t=t+dt; sum=sum+2.0*func(t);
end
t=t+dt; sum=(sum+func(t))*dt/2;
[sum]
end
function fv=func(t)
fv=1-exp(-2*t); end
(and the file name is also 'trapezoid.m')
I know I have to input the values of ta,tb and n on the command tab, so I typed several sets of numbers but none of them gave me answers but this error:
오류: 파일: trapezoid.m 라인: 3 열: 16
함수 'trapezoid'이(가) 이미 이 범위 내에 선언되어 있습니다.
(It means function 'trapezoid' is already proclaimed in the region)

采纳的回答

Sai Sri Pathuri
Sai Sri Pathuri 2020-5-5
编辑:Sai Sri Pathuri 2020-5-5
In your script trapezoid, the function trapezoid is treated as a local function and hence, it cannot have same name as that of script.
clc % This is treated as command to be executed and trapezoid, func are local function
function f_int=trapezoid(ta,tb,n)
% code
end
function fv=func(t)
% code
end
This issue can be ressolved in two ways
  1. You may remove clc from the script
  2. You may change the name of script and call the function after clc command
clc
f_int=trapezoid(ta,tb,n); % Replace ta, tb, n by suitable values
function f_int=trapezoid(ta,tb,n)
% code
end
function fv=func(t)
% code
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 명령 입력 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!