# Same code, different result????

5 views (last 30 days)
Byeongchan Min on 29 Apr 2020
Edited: Sai Sri Pathuri on 5 May 2020
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 on 5 May 2020
Edited: Sai Sri Pathuri on 5 May 2020
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