Simple function question.

11 vues (au cours des 30 derniers jours)
Danny C
Danny C le 8 Sep 2016
Commenté : Henry Giddens le 8 Sep 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 commentaire
Henry Giddens
Henry Giddens le 8 Sep 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);

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 8 Sep 2016
all(sign(diff(A)) == sign(diff(B)))
  1 commentaire
Henry Giddens
Henry Giddens le 8 Sep 2016
Didn't see this, even better!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Scope Variables and Generate Names dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by