Advertisement
makispaiktis

Heron's Formula

Jun 10th, 2024
588
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.89 KB | None | 0 0
  1. clear all
  2. close all
  3. clc
  4.  
  5. %% 1. Create the parameters
  6. % 1a. Create 360 points of a circle
  7. R = 100;
  8. theta_moires = 0 : 359;
  9. theta = theta_moires * pi/180;
  10. x = R * cos(theta);    y = R * sin(theta);
  11. Q = [x; y];
  12. plot(x, y, 'blue');
  13. hold on
  14.  
  15. % 1b. Select N points (by index) from this circle
  16. NUM_POINTS = 10;
  17. random_indices = randperm(length(theta), NUM_POINTS);
  18. random_indices = sort(random_indices);
  19. points = Q(:, random_indices);
  20. x = points(1, :);
  21. y = points(2, :);
  22. plot(x, y, 'blacko');
  23.  
  24. % 1c. Logs
  25. fprintf("There are %d points with index:\n\n", NUM_POINTS);
  26. for i = 1 : NUM_POINTS
  27.     fprintf("%d ---> [%.2f, %.2f]\n", random_indices(i), x(i), y(i))
  28. end
  29. fprintf("\n\n\n");
  30.  
  31.  
  32. %% 2. Calculate areas
  33. % 2a. Create the colors (3x7 array)
  34. colors = [1 0 0; 0 1 0; 0 0 1; 0 1 1; 1 0 1; 1 1 0; 0 0 0]';
  35. SIZE = size(colors, 2);
  36.  
  37. % 2b. Take the successive triangles
  38. figure();
  39. plot(x, y, 'blacko');
  40. hold on
  41. total_area = 0;
  42. for i = 1 : NUM_POINTS-2
  43.     which = [1 i+1 i+2];
  44.     vector = points(:, which);
  45.     area = heron(vector);
  46.     total_area = total_area + area;
  47.     fprintf("E%d = %.2f m^2\n", i, area);
  48.     color_column = mod(i, SIZE) + 1;
  49.     plot(points(1, which), points(2, which), 'Color', colors(:, color_column));
  50.     hold on
  51.     plot([points(1, 1) points(1, i+2)], [points(2, 1) points(2, i+2)], 'Color', colors(:, color_column));
  52. end
  53. fprintf("\nE = %.2f m^2 = %.2f acres", total_area, total_area/1000);
  54.  
  55.  
  56.  
  57. %% Auxiliary Functions
  58. function area = heron(vector)
  59.     % vector is ALWAYS 2x3, for the 3 points
  60.     p1 = vector(:, 1);  p2 = vector(:, 2);  p3 = vector(:, 3);
  61.     % Triangle sides
  62.     a = dist(p1, p2);
  63.     b = dist(p1, p3);
  64.     c = dist(p2, p3);
  65.     tau = (a+b+c) / 2;
  66.     area = sqrt(tau * (tau-a) * (tau-b) * (tau-c));
  67. end
  68.  
  69. function d = dist(p1, p2)
  70.     x1 = p1(1);    x2 = p2(1);    y1 = p1(2);    y2 = p2(2);
  71.     d = sqrt((x2-x1)^2 + (y2-y1)^2);
  72. end
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement