How to check whether a 2d matrix is gradually increasing in values in row direction.

3 次查看(过去 30 天)
Lets say u have a matrix A=[2 4 7;3 4 6;] So we can see the A(4)==3 in row 2 has increased from A(1)==2 progression,
And the 6th element,A(6)==6 has reduced from being A(3)==7 to 6.
So the A(6) needs to be replaced by Nan
This is basically the thing. Needs to be done in a large matrix. Any ideas on doing it faster than for loops.

采纳的回答

Stephen23
Stephen23 2017-9-22
编辑:Stephen23 2017-9-22
Using cummax is simple:
>> A = [2,4,7;3,4,6]
A =
2 4 7
3 4 6
>> A(A<cummax(A,1)) = NaN
A =
2 4 7
3 4 NaN
EDIT: to also ignore adjacent repeated values:
>> A = [2,4,7;3,4,6]
A =
2 4 7
3 4 6
>> idx = A<cummax(A,1) | 0==diff([NaN*A(1,:);A],1,1);
>> A(idx) = NaN
A =
2 4 7
3 NaN NaN
  4 个评论

请先登录,再进行评论。

更多回答(3 个)

Andrei Bobrov
Andrei Bobrov 2017-9-22
B = cummax(A);
A([false(1,size(A,2));diff(B)==0]) = nan;

Cedric
Cedric 2017-9-21
编辑:Cedric 2017-9-21
>> flags = [false( 1, size( A, 2 )); diff( A ) < 0]
flags =
2×3 logical array
0 0 0
0 0 1
>> A(flags) = NaN
A =
2 4 7
3 4 NaN
EDIT 5:40pm EST:
>> A = [5, 3, 4, 6; 2, 4, 2, 3].'
A =
5 2
3 4
4 2
6 3
>> select = any((A-permute(A,[3,2,1])) .* permute(tril(ones(size(A,1)*[1,1]),-1),[1,3,2]) < 0, 3)
select =
4×2 logical array
0 0
1 0
1 1
0 1
>> A(select) = NaN
A =
5 2
NaN 4
NaN NaN
6 NaN
and if you have an old version of MATLAB, the expansions must be performed using BSXFUN:
select = any(bsxfun(@times, bsxfun(@minus, A, permute(A, [3,2,1])), ...
permute(tril(ones(size(A, 1) * [1,1]), -1), [1,3,2])) < 0, 3) ;

Image Analyst
Image Analyst 2017-9-21
Of course, simply use conv2():
A=randi(9, 10, 3)
zeroRow = zeros(1, size(A, 2))
m = [zeroRow; conv2(A, [1;-1], 'valid')]
A(m<0) = nan
  2 个评论
MSP
MSP 2017-9-21
But the code isnt doing what I wanted though.From the image I posted you can view what I mean,like the 3 should be replaced by Nan,otherwise its not maintaining the sequence of gradual increasing value.which in case of interpolation of missing values will lead to the same scenario again
Image Analyst
Image Analyst 2017-9-22
Well whatever was after the 9 was less than a 9, let's say it was a 1. So then the 1 goes to a NAN, but 3 is more than the 1 so it gets kept.
What you want is a moving peak detector. I don't think MATLAB has a movpeak() function but I think I saw someone make one in effect through some trick. Of course you could just to a for loop which should be fast as long as your array doesn't have millions of rows.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by