How to write conditional statement/loop?

4 ビュー (過去 30 日間)
Ranjan Kandasamy
Ranjan Kandasamy 2021 年 9 月 7 日
編集済み: Jan 2021 年 9 月 10 日
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))));

採用された回答

Jan
Jan 2021 年 9 月 7 日
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 件のコメント
Ranjan Kandasamy
Ranjan Kandasamy 2021 年 9 月 7 日
So, a If Else statement doesn't work here?
Jan
Jan 2021 年 9 月 7 日
編集済み: Jan 2021 年 9 月 10 日
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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by