histogram of angles in a loop

4 vues (au cours des 30 derniers jours)
SINDU GOKULAPATI
SINDU GOKULAPATI le 8 Mai 2021
for i=1:n
for j=1:n
angle = transpose(rnorm{i})*rnorm{j};
if angle < cosd(20)
here for every 'i' i want histogram wrt to angles
end
end
end
i need to transform the above code in such a way that for each 'i' histogram(angles) [gap of 0.5 upto 20] has to be stored
rnorm is a 3*1 matrix
urs help is highly appretiated thanks

Réponses (1)

Vidhi Agarwal
Vidhi Agarwal le 27 Nov 2024
To transform your code such that for each i, you calculate the histogram of angles with a specific bin width and store these histograms, you can follow these steps.
  • Iterate over each pair (i, j), calculate the angle, and if it meets the condition, store it in a list. After processing all pairs for a given i, we'll compute the histogram and store it.
Sample code for the same is gievn below:
% Sample data
n = 10;
rnorm = arrayfun(@(x) rand(3, 1), 1:n, 'UniformOutput', false); % Example 3x1 vectors
% Preallocate a cell array to store histograms
histograms = cell(n, 1);
% Define the bin edges for the histogram
binEdges = 0:0.5:20;
% Loop through each 'i'
for i = 1:n
angles = []; % Initialize an array to store angles for this 'i'
for j = 1:n
% Calculate the dot product and normalize it
dotProduct = transpose(rnorm{i}) * rnorm{j};
normProduct = norm(rnorm{i}) * norm(rnorm{j});
% Ensure the value is within the valid range for acosd
cosTheta = dotProduct / normProduct;
cosTheta = min(max(cosTheta, -1), 1); % Clamp the value
% Calculate the angle in degrees
angle = acosd(cosTheta);
% Check the angle condition
if angle < 20
angles(end + 1) = angle; % Append the angle to the list
end
end
% Compute and store the histogram for the current 'i'
histograms{i} = histcounts(angles, binEdges);
end
% Display the histograms for each 'i'
for i = 1:n
figure;
histogram('BinEdges', binEdges, 'BinCounts', histograms{i});
title(['Histogram of Angles for i = ', num2str(i)]);
xlabel('Angle (degrees)');
ylabel('Frequency');
end
For better understanding of "histcounts" refer to the documentation: https://www.mathworks.com/help/matlab/ref/double.histcounts.html
Hope that helps!

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by