For Loop using two variables
178 次查看(过去 30 天)
显示 更早的评论
I am new to MATLAB and I am trying to use a for loop using two variables. The question is: Generate a MATLAB program to compute and plot the Fermi function, f(E), and 1- f(E) versus ΔE = E-Ef for values of ΔE that is over the range of -0.5eV ≤ ΔE ≤ 0.5eV for varying temperature settings where Temperature = 150, 250, 350, 450 and 550K.
The code I have written is:
k = 1.3806488*10^-23; %boltzman constant
format shortEng
for dE = linspace (-0.5, 0.5, 5), T1 = 150:100:550
fE = 1/(1+exp(dE/(k*T1))) %Fermi Function
fE2 = 1-fE
end
However, it its only displaying T1
0 个评论
回答(1 个)
Andrew Newell
2014-4-24
编辑:Andrew Newell
2014-4-24
You need to use a couple of nested loops:
k = 1.3806488*10^-23; %boltzman constant
format shortEng
for dE = linspace (-0.5, 0.5, 5)
for T1 = 150:100:550
fE = 1/(1+exp(dE/(k*T1))) %Fermi Function
fE2 = 1-fE
end
end
For plotting these results, however, you'll need to store the values in a matrix, like this:
dE = linspace(-0.5,0.5,5);
T1 = 150:100:550;
fE = zeros(length(dE),length(T1)); % initializing fE speeds up the calculation
for i=1:length(dE)
for j=1:length(T1)
fE(i,j) = 1/(1+exp(dE/(k*T1))); %Fermi Function
end
end
fE2 = 1-fE; % No need to put this in the loop
4 个评论
Torsten
2024-11-13,14:05
I think fE is meant as a matrix with
fE(i,j) = 1 / (1+exp(deltaE(i)/(k*Temp(j))))
DGM
2024-11-13,15:41
编辑:DGM
2024-11-13,15:56
Consider:
% inputs
k = 1.3806488*10^-23; %boltzman constant
dE = linspace(-0.5,0.5,5);
T1 = 150:100:550;
% you could use loops
fE = zeros(length(dE),length(T1)); % initializing fE speeds up the calculation
for i = 1:length(dE)
for j = 1:length(T1)
fE(i,j) = 1/(1 + exp(dE(i)/(k*T1(j)))); % Fermi Function
end
end
fE2_0 = 1-fE % No need to put this in the loop
% or just calculate the entire output at once
% assuming both inputs are row vectors to begin with
fE2_1 = 1 - 1./(1 + exp(dE.'./(k*T1)))
% that wouldn't have been an option when this was posted.
% prior to R2016b, this is how it would be done
fE2_2 = 1 - 1./(1 + exp(bsxfun(@rdivide,dE.',k*T1)))
Note that this looks odd because these are tiny numbers (actually several orders of magnitude smaller than floating point resolution for the numerator).
(k*T1)
As a consequence, these are huge numbers being fed to an exponential function
dE.'./(k*T1)
... and so we're excessively sensitive to dE and we lose all sensitivity to T1:
exp(dE.'./(k*T1))
You should probably want to rethink how you want to solve a problem like this. Naive floating point numeric calculations might not be the way to go.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calendar 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!