I have been trying to create a piecewise linear model of a diode through curve fitting. While trying to implement the code below, I ran into a strange bug that is causing my output curve to shift to be roughly -0.2, the max value of the graph, as you can see in the picture below. The same problem occurs when the range of vd is shifted or an xlim is added to the graph. If you have any ideas, please let me know.
Thanks!
value :
%% variables
Is=1e-12; % Saturation current (in Amperes)
n = 2; % Ideality factor (typically between 1 and 2)
T = 300; % Temperature in Kelvin
k = 1.380649e-23; % Boltzmann constant (J/K)
q = 1.602176634e-19; % Electron charge (C)
% Calculate thermal voltage
vt=(k*T)/q; % Thermal voltage (in Volts)
vd=0:0.01:10; % Voltage range from -0.1V to 1V
%figure, plot(time,v1);
%% diode model calculations
%calculate the current voltage relation ship for the diode
Id_s=Is.*(exp((vd/(n*vt)))-1); %calcuate diode current using shockley's equation
%plot schokley eq
figure,
plot(vd, Id_s); % Use a logarithmic scale for current
xlabel('V_d (V)'); % Label for the x-axis (Voltage)
ylabel('I_d (A)'); % Label for the y-axis (Current)
title('Shockley equation diode model');
grid on;
%% curve fitting
range_1=0.74:0.01:0.88; %define range for the first curve piece
range_2=0.89:0.01:max(vd); %define range for the second curve piece
Id_fit1=polyfit(range_1,Id_s(find(vd==0.74):find(vd==0.88)),1); %fit a line to the first part of the curve
Id_fit2=polyfit(range_2,Id_s(find(vd==0.89):find(vd==max(vd))),1);%fit a line to the second part of the curve
line_1=polyval(Id_fit1,range_1);
line_2=polyval(Id_fit2,range_2);
Id_fit=[zeros(1,length(vd)-length(range_1)-length(range_2)),line_1, line_2]; %create a combine vector of each piece wise component
figure,
plot(vd, Id_s); % Use a logarithmic scale for current
xlabel('V_d (V)'); % Label for the x-axis (Voltage)
ylabel('I_d (A)'); % Label for the y-axis (Current)
title('Shockley equation diode model');
grid on;
hold on
plot(vd,Id_fit);
legend('Shockley Curve, Curve Fit')