%Measured Values
Uds=[2.40 2.52 2.59 2.71 2.93 3.12];
Id=[10 20 30 50 100 150];
IdSqrt=Id.^(1/2);

%Plot Id Uds
hold off
subplot(3,1,1);
plot(Uds,Id, '-k');
hold on


grid on
%ylim([1, 5]);
xlim([1.5,3.5]);
xlabel('Uds = Ugs [V]');
ylabel('Id [mA]');


%Plot Sqrt(Id) Uds
subplot(3,1,2);hold off
plot(Uds, IdSqrt, 'xk');
grid on
xlim([1.5,3.5]);
ylim([0,20]);
xlabel('Uds = Ugs [V]');
ylabel('Sqrt(Id) [mA]');
hold on

%Line of best fit Sqrt(Id) Uds
coeffs = polyfit(Uds, IdSqrt, 1);
% Get fitted values
fittedX = linspace(0, max(Uds), 200);
fittedY = polyval(coeffs, fittedX);
% Plot the fitted line
hold on
subplot(3,1,2);
plot(fittedX, fittedY, 'r-');

%Line equation
% m = (y2 ? y1)/(x2 ? x1).
m = (fittedY(200) - fittedY(1))/(fittedX(200) - fittedX(1))
%Equation of a line:= (y-y1) = m(x-x1).
%Rearranged to produce x-intercept, y=0.
%Ut = Uthreshold = x.
Ut = (0-fittedY(200))/m + fittedX(200);
%Pretty green plotpoint for Ut with arrow & value
plot(Ut, 0, 'xg');
str=['\downarrowUt = ', num2str(Ut), ' [V]'];
text(Ut, 2, str)

%Calculate K from the line of best fit.
%Using the equation Id=(k/2)*((UGS-Ut)^2)  and the fact that in this case
%UGS = Uds (voltage over drain-source & gate-source are equal)
%We rearrange to get: K = (2*Id)/((Uds-Ut)^2)

%!!!Unnecessary to calculate whole matrix of values as K is constant!!!
%K = (2.*(fittedY.^2))./((fittedX-Ut).^2)

%In one point only
K = (2*(fittedY(2)^2))/((fittedX(2)-Ut)^2);
%fittedY:=sqrt(Id) and so it is squared to obtain Id.
%fittedX:=Uds=UGS
K = K/1000  %Working in mA range.
str1 =['K = ', num2str(K), ' [A/V^2]'];
text(3, 4, str1)
hold on

%Power plot
%Pmos = Uds*Id       Presistor = (Id^2)*R
powermos = (Id./1000).*Uds;
powerres = ((Id./1000).^2)*100;

subplot(3,1,3);hold on
ylabel('P [W]')
xlabel('Uds = Ugs [V]')
plot(Uds, powermos,'-b')
hold on
plot(Uds, powerres,'-r')
xlim([1.5,3.5]);
grid on
