필터 지우기
필터 지우기

how to find out wether the array is Hill or not?

조회 수: 2 (최근 30일)
aya qassim
aya qassim 2019년 1월 1일
댓글: aya qassim 2019년 1월 1일
Hey,
If I have an array of numbers for example
a=[1,2,2,3,3,4,4,2,-1,-1]
this array has two series: one is an Ascending series of numbers[1,2,2,3,3] , two is a descending series of numbers [4,4,2,-1,-1] an array which contains this two series is caled a Hill.
note: it still can be a descending or ascendings if the numbers in the array are equal
so how can I find out if it a Hill
I tried to use the "For" loops but matlab said that the matrix deminisions are not okay I did mot understand why?
any help please?
thank you,

채택된 답변

the cyclist
the cyclist 2019년 1월 1일
편집: the cyclist 2019년 1월 1일
I think this is right, but I have to admit I have not thoroughly checked it:
% Original data
a=[1,2,2,3,3,4,4,2,-1,-1];
% Find difference between consecutive elements
s = diff(a);
% Find the last "uphill" element, and the first "downhill" element
u = find(s>0,1,'last');
d = find(s<0,1,'first');
% Make sure the last uphill element occurs before the first downhill element
is_hill = u<d
The variable is_hill will be true if a is a "hill", and false if not.

추가 답변 (1개)

Elijah Smith
Elijah Smith 2019년 1월 1일
This is just the first thing that I thought of:
function res = Is_hill(array)
%define variables
res = -1;
stopVar = 0;
%for the given array
for j = 1:(length(array) - 1)
%is the array rising:
if array(j) <= array(j + 1)
%if it is, keep going
continue;
else
%once it stops rising note the element it stopped at:
stopVar = j;
%exit the loop:
break;
end
end
%if it did increase and is now decreasing:
if stopVar > 1
%make sure it doesn't increase again (causing a wave not a hill):
for ii = stopVar:(length(array)-1)
%if it is decreasing
if array(ii) >= array(ii + 1)
%then go check next set of elements:
continue;
else
%if it starts to increase again then it is not a hill
res = false;
break;
end
end
else
%if it never increase or never decrease then it is not a hill:
res = false;
end
%if it's not false it must be true:
if res ~= false
res = true;
elseif res == -1
%if res hasn't changed, there was an error:
error("there was an error")
end
end
You might want to change it to fit your needs.

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by