Simple function question.

3 visualizaciones (últimos 30 días)
Danny C
Danny C el 8 de Sept. de 2016
Comentada: Henry Giddens el 8 de Sept. de 2016
I'm trying to create a function that checks whether of not the contour of two vectors is the same. What I mean by contour is whether adjacent elements of the vector are increasing or decreasing.
For example : v1 = [3, 8, 7] , v2 = [20, 21, -10] , the outcome should be true since the both vectors increase and then decrease. On the other hand, if it becomes like v3 = [3, 0, -10], v4 = [5, 1, 21], the outcome should be false since the contours of the both vectors don't agree with each other.
I already made a function and it's perfectly working fine. But I was just wondering what are the other ways to solve this problem without using logicals and if-elseif-else. (or other ways using logicals and if-elseif-else) - so basically, any other ways.
+++If you can also come up with function that can be used in any kind of situations as well(not only 1*3 vector situation, but even if you don't really know the dimension of the vectors.) I would be really glad. Thank you!
-----
This is the function I came up in like 2 minutes so it's very simple but working.
function [log] = checkContour(V1, V2)
A = diff(V1);
B = diff(V2);
if A(1)>0 & A(2)>0 & B(1) & B(2)
log = 1 ;
elseif A(1)<0 & A(2)<0 & B(1)<0 & B(2)<0
log = 1 ;
elseif A(1)>0 & A(2)<0 & B(1)>0 & B(2)<0
log = 1 ;
elseif A(1)<0 & A(2)>0 & B(1)<0 & B(2)>0
log = 1 ;
elseif A(1)==0 & A(2)==0 & B(1)==0 & B(2)==0
log = 1 ;
else
log = 0 ;
end
end
  1 comentario
Henry Giddens
Henry Giddens el 8 de Sept. de 2016
Of the top of my head, how about...
A = diff(V1);
B = diff(V2);
A = A./abs(A);
B = B./abs(B);
log = all(A == B);

Iniciar sesión para comentar.

Respuestas (1)

Walter Roberson
Walter Roberson el 8 de Sept. de 2016
all(sign(diff(A)) == sign(diff(B)))
  1 comentario
Henry Giddens
Henry Giddens el 8 de Sept. de 2016
Didn't see this, even better!

Iniciar sesión para comentar.

Categorías

Más información sobre Scope Variables and Generate Names en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by