For Loop using two variables
37 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Andrew Newell
am 24 Apr. 2014
Bearbeitet: Andrew Newell
am 24 Apr. 2014
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 Kommentare
Torsten
am 13 Nov. 2024
I think fE is meant as a matrix with
fE(i,j) = 1 / (1+exp(deltaE(i)/(k*Temp(j))))
DGM
am 13 Nov. 2024
Bearbeitet: DGM
am 13 Nov. 2024
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.
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!