Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
looking for an index and value in array

Subject: looking for an index and value in array

From: muzaffar

Date: 1 Dec, 2008 16:11:02

Message: 1 of 3

Dear All,
if c=[1 1 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 1 1 0 0 1 1 1 1 1 1]
how i can count no.of 1's between zeros. So i need to calculate numbers of 1's before a value zero and index of last 1 just before zero.
thanks
regards

Subject: looking for an index and value in array

From: Walter Roberson

Date: 1 Dec, 2008 17:13:13

Message: 2 of 3

muzaffar wrote:

> if c=[1 1 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 1 1 0 0 1 1 1 1 1 1]
> how i can count no.of 1's between zeros. So i need to calculate numbers of 1's before
> a value zero and index of last 1 just before zero.

It isn't clear if you need this only for the first case, or repeatedly within the vector.
If you only need the first, then:

find(~c,1)-1

Note: if the array begins with a 0, then this will report that there were zero 1's before
the zero, which would be correct but perhaps not what you would want...

--
.signature note: I am now avoiding replying to unclear or ambiguous postings.
Please review questions before posting them. Be specific. Use examples of what you mean,
of what you don't mean. Specify boundary conditions, and data classes and value
relationships -- what if we scrambled your data or used -Inf, NaN, or complex(rand,rand)?

Subject: looking for an index and value in array

From: Roger Stafford

Date: 2 Dec, 2008 06:10:20

Message: 3 of 3

"muzaffar" <muzaffarbashir@yahoo.com> wrote in message <gh12am$kqi$1@fred.mathworks.com>...
> Dear All,
> if c=[1 1 1 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 1 1 0 0 1 1 1 1 1 1]
> how i can count no.of 1's between zeros. So i need to calculate numbers of 1's before a value zero and index of last 1 just before zero.
> thanks
> regards

  I assume from your description that in your example you want a set of counts of 1, 7, and 2 for the three groups of 1's surrounded by 0's and indices 11, 21, and 28 for the 1's which were last in each such group of 1's. In other words, the initial eight 1's and the final six 1's are not to be counted since they are not surrounded at both ends by 0's? Is that correct? If so, you can compute them this way:

 t = diff([1,c,1]);
 cnt = find(t==1); cnt = cnt(1:end-1);
 ind = find(t==-1); ind = ind(2:end)-1;
 cnt = ind-cnt+1;

The counts and indices are given by arrays 'cnt' and 'ind', respectively.

Roger Stafford

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us