Calculating the sum of a quantity
4 views (last 30 days)
Show older comments
Hello,
I am trying to calculate the angles_ave_0LT using the following code but the majority of elements of angles_sum_0LT has a NaN error (although it's only a summation). The values come from a raw data that the matrix G includes. How do I fix this propblem escpecially in angles_sum_0LT?
G = [totaldistance2840LTfxn(:,2),totalangles2840LT(:,2)];
zmin_0LT = min(G(:,1));
zmax_0LT = max(G(:,1));
binsize_0LT = 0.03;
n_bins_0LT = (zmax_0LT-zmin_0LT)/binsize_0LT + 1;
histo_0LT(1:n_bins_0LT,1) = 0;
angles_sum_0LT(1:n_bins_0LT,1) = 0;
L_nbins_0LT = [0:n_bins_0LT-1];
zbin_0LT = binsize_0LT*L_nbins_0LT + zmin_0LT + 0.5*binsize_0LT;
for i = 1:length(G(:,1))
binid_0LT = floor((G(i,1) - zmin_0LT)/binsize_0LT) + 1;
bin_id_0LT(i) = binid_0LT;
histo_0LT(binid_0LT,1) = histo_0LT(binid_0LT,1) + 1;
angles_sum_0LT(binid_0LT) = angles_sum_0LT(binid_0LT) + G(i,2);
end
angles_ave_0LT = angles_sum_0LT./histo_0LT;
figure
plot(zbin_0LT,angles_ave_0LT,"LineWidth",2,"Color",[0.6350 0.0780 0.1840]); hold on
axis square
set(gca,'linewidth',1)
set(gca,'XMinorTick','on')
set(gca,'YMinorTick','on')
set(gca,'linewidth',1)
ax = gca;
ax.FontSize = 20;
ylabel("Angles");
xlabel("z (nm)");
xlim([-4.05 4.05]);
0 Comments
Answers (1)
Steven Lord
on 3 May 2023
Are you trying to bin the data and then compute the mean in each bin? If so consider using findgroups or discretize to determine into which bin each element of the data falls then groupsummary to take the mean of the data in each group or bin.
Elements of angles_sum_0LT could be NaN if any of the elements in G that you were adding to that element were non-finite (most commonly NaN, but adding Inf to the element at one iteration then adding -Inf to that same element at a later iteration or vice versa would do.)
y = Inf - Inf
I'd expect elements of angles_ave_0LT to be more likely to be NaN if those bins contain no data from G. That would give you 0/0.
x = 0/0
See Also
Categories
Find more on Particle & Nuclear Physics 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!