Find maximum number of consecutive negative values

Hi,
I have a mxn matrix and I need to find the maximum number of consecutive negative values for each column.
So the output would be a 1xn vector, where the i-th element is the maximum number of consecutive negative values for column "i".
How would I do this without a loop?

댓글 수: 1

dave
dave 2013년 8월 21일
Thanks everybody for your great suggestions - I wish I could accept more than one answer...

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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 8월 21일

0 개 추천

A = randi([-6,3],20,15); % Let it your array
t = A < 0;
s = size(t);
tt = cumsum(diff([false(1,s(2));t]) == 1);
[jj,jj] = ndgrid(zeros(1,s(1)),1:s(2));
out = max(accumarray([tt(t),jj(t)],ones(nnz(t),1)));

댓글 수: 1

What to do, if I want to know the starting index of the maximum consecutive negative elements. Thank you in advance

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

추가 답변 (2개)

Iain
Iain 2013년 8월 20일

0 개 추천

logi = x < 0;
[bw n] = bwlabel(logi);
A = regionprops(bw,'Area');
Answer = max([A(:).Area]);

댓글 수: 2

regionprops() is in the Image Processing Toolbox. With later versions, it can do the labeling automatically internally:
x = array2D(:, columnNumber); % Extract just this column
negativeValues = x < 0; % Logical array
structureA = regionprops(negativeValues,'Area');
Answer = max([structureA.Area]);
Repeat for every column in your array.
What to do, if I want to know the starting index of the maximum consecutive negative elements. Thank you in advance

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

Roger Stafford
Roger Stafford 2013년 8월 20일

0 개 추천

If you want the code completely vectorized, let x be your matrix and do this:
[m,n] = size(x);
p = double([0;reshape([x;zeros(1,n)],[],1)]<0);
f = find(diff(p)~=0);
f2 = f(2:2:end);
p(f2+1) = f(1:2:end-1)-f2;
p = cumsum(p);
p = reshape(p(2:end),[],n);
mx = max(p); % mx is the required 1 x n row vector of column maxima
However, I suspect that a single for-loop, properly done, would be faster.

댓글 수: 1

What to do, if I want to know the starting index of the maximum consecutive negative elements. Thank you in advance

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2013년 8월 20일

댓글:

2021년 3월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by