Why are the results of the iterative calculations different?

2 ビュー (過去 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 Center および File ExchangeProgramming についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by