How to calculate the number of consecutive negative values in an array before a positive appears?

조회 수: 3 (최근 30일)
I am writing a code, where the output is as follows:
c =
-0.4607 -0.4659 -0.5165 -0.5168 -0.5164 -0.4626 -0.4668 -0.3730 -0.3426 0.3224
0.3251 0.3270 0.3281 0.3400 -0.1816 -0.1830 -0.1851 1
I want to calculate the number of negative values before a positive value appeares for each cases. How do I do that?

채택된 답변

Image Analyst
Image Analyst 2021년 7월 29일
Here's another way:
c =[-0.4607 -0.4659 -0.5165 -0.5168 -0.5164 -0.4626 -0.4668 -0.3730 -0.3426 0.3224 ...
0.3251 0.3270 0.3281 0.3400 -0.1816 -0.1830 -0.1851 1]
props = regionprops(c<0, 'Area'); % Measure lengths of all runs of negative values.
results = [props.Area] % [9, 3] % Turn from structure into a vector.
  댓글 수: 3
Tawsif Mostafiz
Tawsif Mostafiz 2021년 7월 30일
Thanks everyone! I have another problem. Suppose the output is like this:
results =
1 14 3 14
Now suppose I want to find the count of numbers (both positive and negative) before the maximum count of negative numbers appears. As the maximum 14 comes twice and I need the first instance, I am calculcating the maximum by this:
maximum=max(results);
location=find(results==maximum,1);
Now, how do I calculate, how many numbers appear before it?
Image Analyst
Image Analyst 2021년 7월 30일
That number is simply the location minus 1. So it finds 14 at location 2 for the max, and there is one number, 1, before that location.

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

추가 답변 (1개)

Adam Danz
Adam Danz 2021년 7월 29일
c = [-0.4607 -0.4659 -0.5165 -0.5168 -0.5164 -0.4626 -0.4668 -0.3730 -0.3426 0.3224 ,...
0.3251 0.3270 0.3281 0.3400 -0.1816 -0.1830 -0.1851 1];
A = c(:)<0;
B = diff(find([0,A(:).',0]==0))-1;
B(B==0) = []
B = 1×2
9 3

카테고리

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

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by