If statement not working for trig quad check
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Andrew Matteson
el 18 de Sept. de 2023
Comentada: the cyclist
el 18 de Sept. de 2023
Hello all,
I've tried to make a simple trig quad check progam for one of my school classes, but I've ran into an error on the if statement that returns what angle my cartesian vector points to. I know that the math is correct and working as seen in the output, but the if statement is not selecting the correct value even though I'm pretty sure that the code should be.
Here is the code and output:
clear all
close all
clc
% Sample vectors
vec1 = [0.8373, 2.9192];
vec2 = [2.0376, 1.2927];
vec3 = [2.0508, -0.7287];
vec4 = [0.8720, -2.3708];
vec5 = [-1.0475, -3.0047];
vec6 = [-2.9724, -2.3876];
vec7 = [-4.1656, 0.7559];
vec8 = [-4.1700, 1.2655];
vec9 = [-2.9840, 2.9025];
vec10 = [-1.0618, 3.5280];
% Matrix with line-by-line function. For output readability
vel = [cart2polar(vec1); cart2polar(vec2); cart2polar(vec3);...
cart2polar(vec4); cart2polar(vec5); cart2polar(vec6); ...
cart2polar(vec7); cart2polar(vec8);cart2polar(vec9); ...
cart2polar(vec10)];
velT = array2table(vel,"VariableNames",{'Magnitues','Angle','Asin', ...
'pi-sin', 'cosine','2pi-cosine'});
disp(velT)
Correct values are the values of sine and cosine that match in magnitude.
Row 3 would be 1.9122
Row 7 would be 1.3913
% Function
function vec_o = cart2polar(vec_i)
% Magnitude of vector
v = norm(vec_i);
% Returns sine and cosine values
theta_s = [asin(vec_i(1)/v), pi-asin(vec_i(1)/v)];
theta_c = [acos(vec_i(2)/v), 2*pi-acos(vec_i(2)/v)];
% Combines as vector
theta = [theta_s, theta_c];
gamma = 0;
% If statement
if (theta(1) == theta(3)) && (theta(1) ~= theta(2)) && (theta(1) ~= theta(4))
gamma = theta(1);
% Quad 1
elseif theta(2) == theta(3) && (theta(2) ~= theta(1)) && (theta(2) ~= theta(4))
gamma = theta(2);
% Quad 2
elseif theta(2) == theta(4)
gamma = theta_c(2);
% Quad 3
elseif -theta(1) == theta(3)
gamma = 2*pi-theta_c(1);
% Quad 4
else
end
% Returns values
vec_o = [v, gamma, theta];
end
Thanks to anyone ahead of time
Respuesta aceptada
the cyclist
el 18 de Sept. de 2023
Editada: the cyclist
el 18 de Sept. de 2023
I did not look in detail, but I'd be willing to bet that the problem lies in making comparisons between floating-point numbers, which may not be represented exactly.
Try making those comparisons to within a tolerance, for example
if abs(theta(1)-theta(3)) < 1.e-9
3 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Function Creation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!