Same code, different result????

조회 수: 6 (최근 30일)
Byeongchan Min
Byeongchan Min 2020년 4월 29일
편집: Sai Sri Pathuri 2020년 5월 5일
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!