Hi @Jorge Luis Paredes Estacio,
Your most important task in my opinion is to compute the average of a set of angles, taking into account their positions in the circular coordinate system. The average should be calculated in such a way that it correctly reflects the circular nature of angles, avoiding the pitfalls of simple arithmetic averaging which can lead to incorrect results when angles wrap around (e.g., 359 degrees and 1 degree).
function average_angle = calculate_average_angle(angles) % Convert angles to radians angles_rad = deg2rad(angles);
% Calculate the average of the sine and cosine components avg_sin = mean(sin(angles_rad)); avg_cos = mean(cos(angles_rad));
% Calculate the average angle in radians average_rad = atan2(avg_sin, avg_cos);
% Convert the average angle back to degrees average_angle = rad2deg(average_rad);
% Normalize the angle to be within the range [0, 360) if average_angle < 0 average_angle = average_angle + 360; end end
% Example cases angles1 = [2; 355; 0; 6]; average1 = calculate_average_angle(angles1); disp(['Average Angle 1: ', num2str(average1)]);
angles2 = [-2; 350; 0; -3]; average2 = calculate_average_angle(angles2); disp(['Average Angle 2: ', num2str(average2)]);
angles3 = [5; 36; 45; -5]; average3 = calculate_average_angle(angles3); disp(['Average Angle 3: ', num2str(average3)]);
angles4 = [35; 36; 45; 50]; average4 = calculate_average_angle(angles4); disp(['Average Angle 4: ', num2str(average4)]);
angles5 = [180; 150; -8; 130]; average5 = calculate_average_angle(angles5); disp(['Average Angle 5: ', num2str(average5)]);
So, after analyzing this code, you will find out that the angles are first converted from degrees to radians using the deg2rad function which is necessary because trigonometric functions in MATLAB operate in radians. Then, the function calculates the average of the sine and cosine of the angles and this step is crucial as it allows you to account for the circular nature of your angles. Please note that the average sine and cosine values represent the coordinates of the average angle on the unit circle then I used atan2 function to compute the angle from the average sine and cosine values which returns the angle in radians, then converted back to degrees using rad2deg. Finally, the average angle is normalized to ensure it falls within the range of [0, 360) degrees. If the calculated average angle is negative, 360 degrees is added to bring it into the desired range. I tested the function is tested with several sets of your angles, and the results are displayed using the disp function. Please see attached.
![](/matlabcentral/answers/uploaded_files/1759904/IMG_7560.jpeg)
Please let me know if you have any further questions.