Why are the results of the iterative calculations different?
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
VBBV
on 1 Sep 2024
%%%%%%%%%%%%%%%
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 Comments
VBBV
on 1 Sep 2024
@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)
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!