How to write conditional statement/loop?

4 Ansichten (letzte 30 Tage)
Ranjan Kandasamy
Ranjan Kandasamy am 7 Sep. 2021
Bearbeitet: Jan am 10 Sep. 2021
I need to plot with an expression for V<0 and another expression for V>0.
clc
clear all
n = 1.02; %Ideality factor
A = 33.65; %Richardson constant
q = 1.602*10^-19; % electron charge
K = 1.38*10^-23; %Boltzmann constant
T = 300; % Absolute temperature
phi_b = 0.28; %Barrier Height
J_0 = A* (T* T)* exp((-q* phi_b)./(K* T));
V = linspace(0,2);
if V<0
J = -J_0;
else
J = J_0.* exp((q* V)./(n* K* T)).* (1 - (exp(-q* V)./(K* T)));
end
plot(V, log(J ./(1 - exp(-q* V)/(K *T))));

Akzeptierte Antwort

Jan
Jan am 7 Sep. 2021
For V = linspace(0, 2) there is no V < 0. But in general:
V = linspace(-2, 2);
J = J_0.* exp((q * V) ./ (n * K * T)) .* (1 - (exp(-q * V) ./ (K * T)));
J(V < 0) = -J_0;
  2 Kommentare
Ranjan Kandasamy
Ranjan Kandasamy am 7 Sep. 2021
So, a If Else statement doesn't work here?
Jan
Jan am 7 Sep. 2021
Bearbeitet: Jan am 10 Sep. 2021
Of course it would work, but it is slower, less elegant and offers more chances for typos:
V = linspace(-2, 2, 100);
J = NaN(size(V)); % Pre-allocation
for k = 1:numel(V)
if V(k) < 0
J(k) = -J_0;
else
J(k) = J_0 * exp((q * V(k)) / (n * K * T)) * (1 - (exp(-q * V(k)) / (K * T)));
end
end
% Or slightly simpler:
V = linspace(-2, 2, 100);
J = repmat(-J_0, size(V)); % Pre-allocation with default value
for k = 1:numel(V)
if V(k) >= 0
J(k) = J_0 * exp((q * V(k)) / (n * K * T)) * (1 - (exp(-q * V(k)) / (K * T)));
end
end

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by