I need help with using the If-Else loop containing scalar and nonscalar

Create a plot of iD as a function of vDS from 0 ≤ vDS ≤ 8 V, for three values of vGS =2, 3, and 4 V.
Constants: Kn=0.2 mA/V2; VTN =1.2 V; λ=0.01 V-1.
Here is my work I have so far:
Vds = 0:0.1:8;
Vgs = 2:1:4;
kn = 0.2;
Vtn = 1.2;
lambda = 0.01;
Vds_Sat = Vgs - Vtn;
if (Vds <= Vds_Sat)
ID = Kn*(2*(Vgs-Vtn)*Vds - (Vds^2));
else (Vds >= Vds_Sat)
ID = Kn*((Vgs - Vtn)^2*(1 + lambda * Vds));
end
plot(Vds.,ID)
It is telling me I have an error on line 7 and that my matrix dimension must agree, could you please help me with this?

1 Comment

There is no such thing as an "If loop". There is an "if statement". Loops execute the body multiple times; statements execute the body (or not) exactly one time.

Sign in to comment.

Answers (1)

This operation
Vds <= Vds_Sat
does not make sense since the left and right hand side are vectors of different sizes.

9 Comments

How can I make them equal so that I can plot them?
Loop over Vgs and operate on one value at a time
for Vgs=[2,3,4]
Vds_Sat = Vgs - Vtn;
etc...
end
Also, use logical indexing instead of IF...ELSE statements. Also, make sure you know the differences between Vds^2 and Vds.^2
idx = (Vds <= Vds_Sat) ;
ID(idx) = Kn.*(2.*(Vgs-Vtn).*Vds(idx) - (Vds(idx).^2));
Is there a way to do it with and if statement? I'm also not really clear on how to do it with a for loop. We have not been taught indexing in class so I don't know how to do that.
An if-statement when (Vds <= Vds_Sat) is a vector will not do what you want here. Some kind of indexing and/or a for-loop will be necessary. If you want to stay as close as possible to your original code, you could double loop over Vds and Vgs
VDS=0:.1:8;
for Vgs=[2,3,4]
for ii=1:length(VDS)
V_ds=VDS(ii);
Vds_Sat = Vgs - Vtn;
if (Vds <= Vds_Sat)
ID(ii) = Kn*(2*(Vgs-Vtn)*Vds - (Vds^2));
else (Vds >= Vds_Sat)
ID(ii) = Kn*((Vgs - Vtn)^2*(1 + lambda * Vds));
end
end
plot(....)
end
if true
% code
end
Kn = 0.2; %Set value for Kn
Vtn = 1.2; %Set value for Vtn
lambda = 0.01; %Set value for lambda
VDS=0:.1:8;
for Vgs=[2,3,4]
for k=1:length(VDS)
V_ds=VDS(k);
Vds_Sat = Vgs - Vtn;
if (Vds(k) <= Vds_Sat(k))
ID(k) = Kn(k)*(2*(Vgs(k)-Vtn(k))*Vds(k) - (Vds(k)^2));
else (Vds(k) >= Vds_Sat(k))
ID(k) = Kn(k)*((Vgs(k) - Vtn(k))^2*(1 + lambda(k) * Vds(k)));
end
end
plot(VDS,ID)
end
Say if I had the for loop using k instead of ii like you showed me would all the other variable have to be in terms of k. i.e. variable(k)?
I got the plot to work but it only plots the case when Vgs = 4. How can I obtain the plots when Vgs = 2 & 3?
Use the HOLD command. Or, plot to different figure windows
figure; plot(....)

Sign in to comment.

Categories

Asked:

on 21 Jan 2013

Community Treasure Hunt

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

Start Hunting!