Find maximum number of consecutive negative values
Mostrar comentarios más antiguos
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 comentario
dave
el 21 de Ag. de 2013
Respuesta aceptada
Más respuestas (2)
Iain
el 20 de Ag. de 2013
logi = x < 0;
[bw n] = bwlabel(logi);
A = regionprops(bw,'Area');
Answer = max([A(:).Area]);
2 comentarios
Image Analyst
el 20 de Ag. de 2013
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.
DARSHAN N KANNUR
el 24 de Mzo. de 2021
What to do, if I want to know the starting index of the maximum consecutive negative elements. Thank you in advance
Roger Stafford
el 20 de Ag. de 2013
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 comentario
DARSHAN N KANNUR
el 24 de Mzo. de 2021
What to do, if I want to know the starting index of the maximum consecutive negative elements. Thank you in advance
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!