필터 지우기
필터 지우기

Why are the results of the iterative calculations different?

조회 수: 1 (최근 30일)
xin
xin 2024년 9월 1일
편집: Walter Roberson 2024년 9월 1일
Consider the solution for capacitive current,,running different codes gives different results.
%%%%%%%%%%%%%%%
clear
clc
T=1e-3;
t=0:T:1;
u=sin(2*pi*50*t);
y=fcn(u);
plot(t,y)
function y=fcn(u)
T=1e-3;
C=100e-3;
persistent u1
persistent u0
persistent y0
if isempty(u1) u1=0;
end
if isempty(u0) u0=0;
end
if isempty(y0) y0=0;
end
u0=u;
y0=C/T*(u0-u1);
u1=u0;
y=y0;
end
%%%%%%%%%%%%%%%
deltat=1e-3; %calculation step
C=100e-3; %capacitance
t=0:deltat:1;
k=2/(deltat);
i_a(1)=0;
i_b(1)=0;
u=sin(2*pi*50*t);
for n=1:1000
i_b(n+1)=C/deltat*(u(n+1)-u(n));
end
plot(t,i_b)
%%%%%%%%%%%%%%%
Here's another piece of code that gives a different result.

채택된 답변

VBBV
VBBV 2024년 9월 1일
%%%%%%%%%%%%%%%
clear
clc
T=1e-3;
t=0:T:1;
u=sin(2*pi*50*t);
hold on
for k = 1: numel(u)
y(k)=fcn(u(k));
end
plot(t,y)
function y=fcn(u)
T=1e-3;
C=100e-3;
persistent u1
persistent u0
persistent y0
if isempty(u1) u1=0;
end
if isempty(u0) u0=0;
end
if isempty(y0) y0=0;
end
u0=u;
y0=C/T*(u0-u1);
u1=u0;
y=y0;
end
  댓글 수: 2
VBBV
VBBV 2024년 9월 1일
@xin in the first case, you need to pass the input value as scalar to the function fcn , When you do, both codes produce same results
deltat=1e-3; %calculation step
C=100e-3; %capacitance
t=0:deltat:1;
k=2/(deltat);
i_a(1)=0;
i_b(1)=0;
u=sin(2*pi*50*t);
for n=1:1000
i_b(n+1)=C/deltat*(u(n+1)-u(n));
end
plot(t,i_b)
xin
xin 2024년 9월 1일
Thanks,it's very helpful.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by