Checking if an array element is larger than the following elements

조회 수: 4 (최근 30일)
Valtteri Tikkanen
Valtteri Tikkanen 2017년 5월 11일
편집: Stephen23 2017년 5월 11일
So if I have a large array of form A=[1,5,6,4,12...], is there a consistent way of checking if some element A(n), let's say A(3), is larger than the following ones? So in this case, I would like to find out that A(3)>A(4). Also, then I would like to change those elements in a way that any element A(n) is always equal or larger than any of the elements before it. So again, in this case I would like to change my array A from [1,5,6,4,12...] -> [1,4,4,4,12...] or [1, NaN, NaN,4,12,...].
Thank you.
  댓글 수: 3
Valtteri Tikkanen
Valtteri Tikkanen 2017년 5월 11일
편집: Valtteri Tikkanen 2017년 5월 11일
I have tried this:
A=[1,5,6,4,12,14,13];
for i=2:7
if gt(A(i-1),A(i))
A(i-1)=A(i)
end
end
Which produces A=[1,5,4,4,12,13,13]. The problem is that I do not know how reach elements further away, so for example A(2) is not corrected.
Stephen23
Stephen23 2017년 5월 11일
편집: Stephen23 2017년 5월 11일
Try this:
A = [1,5,6,4,12];
for k = numel(A)-1:-1:1
A(k) = min(A(k:k+1));
end

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

채택된 답변

Jan
Jan 2017년 5월 11일
편집: Jan 2017년 5월 11일
This is not hard. Please feel encouraged to try it by your onw.
A = [1,5,6,4,12];
X = A(length(A));
for k = length(A)-1:-1:1
if A(k) > X
A(k) = X; % Or: NaN
else
X = A(k);
end
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by