How to extract the result after each iteration while using for loop?
15 views (last 30 days)
Show older comments
Md. Golam Zakaria
on 4 Feb 2022
Commented: Md. Golam Zakaria
on 4 Feb 2022
I am working with nested for loop. My code seems to work. However I need to extract the result after each iteration and finally plot the result with respect to the iteration value . Can anyone help me doing that.
clc
clear all
close all
%parametrs
Fs= 2.16*10^-5*pi; % Geometrical Factor for sun
Fa=pi; % Geometrical Factor for earth
q=1.6*10^-16; % Electronic Charge
h= 6.626*10^-34; % Plancks Constant
c= 3*10^8; % Speed of light
K = 8.61*10^-5; % Boltzmanns Constant
Ts=5760; % Temparature of the sun
Ta=300; % Ambient Temparature
A=((2*Fs)/((h^3)*(c^2)));
B=((2*Fa)/((h^3)*(c^2)));
%Power Input
Irradiance=@(E) ((q*A).*(E.^2./(exp((E./(K.*Ts))-1))));
Pinput=integral(Irradiance,0,inf);
vdata=0:0.01:1.6;
n=length(vdata);
Jdark=zeros(1,n);
for i=1.55:0.1:3.6
Eg=i;
Absorbrd_Flux=@(E) ((q*A).*(E.^2./(exp((E./(K.*Ts))-1))));
Jsc=integral(Absorbrd_Flux,Eg,inf);
for j=0:0.1:1.6
V=j;
Jd=@(E) ((q*B).*((E.^2./(exp((E-V)./K*Ta)-1))-(E.^2./(exp(E./K*Ta)-1))));
Jdark=integral(Jd,Eg,inf);
Jv=(Jsc-Jdark);
Pv=V.*Jv;
efficiency=Pv/Pinput;
end
Max_Efficiency=max(efficiency)
end
I need to plot Max_efficiency vs Eg or in this case Max_Efficiency vs i
0 Comments
Accepted Answer
Stephen23
on 4 Feb 2022
Edited: Stephen23
on 4 Feb 2022
With MATLAB it is almost always better to loop over indices rather than over data values. That makes it easier to save the data in arrays. For example:
Eg_vec = 1.55:0.1:3.6;
Eg_num = numel(Eg_vec);
output = nan(1,Eg_num); % preallocate the output array.
for k = 1:Eg_num
Eg = Eg_vec(k);
.. the rest of your code in the loop
output(k) = max(efficiency);
end
plot(Eg_vec,output)
Avoid i and j as loop iterators, they are already defined as the imaginary unit.
4 Comments
Stephen23
on 4 Feb 2022
"The results are coming out different."
Different compared to what? As you were not plotting anything before, I do not understand what you are comparing.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!