can I escape the loop
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
I am tring to use the length function the I wrote to caculate the 3 side of a triangle.
array x represent the x coordinates of 3 vertices of a triangle
array y represent the y coordinates of 3 vertices of a triangle
what I did is trying to use a loop to use the first two number in each arrays, then the first and the last one, then the second and the last one. (just because I found the patterns of the next question which I need to use this function)
here is my code, for now it double caculated using the second and the last number, is it possible to escape the loop?
if you can think of a better method please advise as well.
Thank you in advance.
x=[1 4 1];
y=[1 6 10];
%Use the tri_side function to caculate the length of the first triangle
for i=1:length(x)-1
%access the number in array to use in the function
x1=x(i);
x2=x(i+1);
y1=y(i);
y2=y(i+1);
%use the triSide function
result=triSide(x1,x2,y1,y2);
disp(result);
%for the side of the last length
x1=x(i);
y1=y(i);
x2=x(length(x));
y2=y(length(y));
%use the triSide function
result=triSide(x1,x2,y1,y2);
disp(result);
end
%%function that I use to caculate the length
function result=triSide(x1,x2,y1,y2)
%cacluate the length given the 2 coordinates
result=sqrt(((x1-x2)^2+(y1-y2))^2);
end
2 comentarios
Respuestas (1)
Image Analyst
el 12 de Abr. de 2020
Editada: Image Analyst
el 12 de Abr. de 2020
Index the result. So at the bottom of your loop:
result(i) = triSide(x1,x2,y1,y2);
if length(result) > length(unique(result))
% There is a repeat. Break out of the loop.
break; % The term is "break" rather then "escape".
end
Or if you wanted to check only the last two values for a repeat rather than check the entire vector:
result(i) = triSide(x1,x2,y1,y2);
if result(i) == result(i-1)
% The last two values are the same. Break out of the loop.
break; % The term is "break" rather then "escape".
end
2 comentarios
Image Analyst
el 12 de Abr. de 2020
It give you just unique values, so
>> u = unique([4, 9, 5, 5])
u =
4 5 9
If all values are unique, then the vector and it's unique version will be the same length. If there is a repeat, then the unique version will be shorter.
Ver también
Categorías
Más información sobre Loops and Conditional Statements 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!