Simple function question.

조회 수: 12 (최근 30일)
Danny C
Danny C 2016년 9월 8일
댓글: Henry Giddens 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)))
  댓글 수: 1
Henry Giddens
Henry Giddens 2016년 9월 8일
Didn't see this, even better!

댓글을 달려면 로그인하십시오.

카테고리

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