fork download
  1. function [d1, d2, d] = dotangle(u, v)
  2. % Find the number of entries in u and v
  3. m = length(u);
  4. n = length(v);
  5.  
  6. % Check if u and v have the same number of entries
  7. if m ~= n
  8. disp('The dot product is not defined');
  9. d1 = []; d2 = []; d = [];
  10. return;
  11. else
  12. fprintf('Both vectors have %d entries\n', m);
  13. end
  14.  
  15. % Calculate dot products in three different ways
  16. d1 = u' * v; % Method 1: Transpose(u) * v
  17. d2 = 0; % Method 2: Sum of product of corresponding elements
  18. for i = 1:m
  19. d2 = d2 + u(i) * v(i);
  20. end
  21. d = dot(u, v); % Method 3: Using MATLAB built-in dot function
  22.  
  23. % Check if all dot products are the same
  24. if d1 == d2 && d2 == d
  25. fprintf('The code is correct\n');
  26. else
  27. disp('Check the code!');
  28. return;
  29. end
  30.  
  31. % Calculate the angle between the two vectors
  32. norm_u = norm(u);
  33. norm_v = norm(v);
  34.  
  35. % Ensure the vectors are non-zero before calculating angle
  36. if norm_u == 0 || norm_v == 0
  37. disp('One or both vectors are zero, angle is undefined.');
  38. return;
  39. end
  40.  
  41. % Calculate the angle in degrees
  42. cos_theta = d / (norm_u * norm_v);
  43. theta = acosd(cos_theta); % Convert from radians to degrees
  44.  
  45. % Check and display the angle condition
  46. if abs(theta - 90) < 10^(-5)
  47. fprintf('The angle between the vectors is 90 degrees\n');
  48. elseif abs(theta - 0) < 10^(-5)
  49. fprintf('The angle between the vectors is zero degrees\n');
  50. elseif abs(theta - 180) < 10^(-5)
  51. fprintf('The angle between the vectors is 180 degrees\n');
  52. elseif theta < 90
  53. fprintf('The angle between the vectors is acute and its value is %.5f degrees\n', theta);
  54. else
  55. fprintf('The angle between the vectors is obtuse and its value is %.5f degrees\n', theta);
  56. end
  57. end
  58.  
Success #stdin #stdout 0.12s 46548KB
stdin
Standard input is empty
stdout
Standard output is empty