Simple function question.

2 次查看(过去 30 天)
Danny C
Danny C 2016-9-8
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 个评论
Henry Giddens
Henry Giddens 2016-9-8
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);

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2016-9-8
all(sign(diff(A)) == sign(diff(B)))

类别

Help CenterFile Exchange 中查找有关 Scope Variables and Generate Names 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by