How to write conditional statement/loop?

4 vues (au cours des 30 derniers jours)
Ranjan Kandasamy
Ranjan Kandasamy le 7 Sep 2021
Modifié(e) : Jan le 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))));

Réponse acceptée

Jan
Jan le 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 commentaires
Ranjan Kandasamy
Ranjan Kandasamy le 7 Sep 2021
So, a If Else statement doesn't work here?
Jan
Jan le 7 Sep 2021
Modifié(e) : Jan le 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by