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:
problem using while loop

Subject: problem using while loop

From: H Hachem

Date: 29 May, 2012 17:07:06

Message: 1 of 3

Hi ,

I have written the following script to compute the amount of nonzero elements in a matrix:

function [count] = count(mat)
c=0;
i=1;
j=1;
while(i<=size(mat,1))
    while(j<=length(mat))
        if(mat(i,j)~=0)
            c=c+1;
        end
        j=j+1;
    end
    i=i+1;
end
c
end

However it seems the 1st while loop seems not working, while the second works normally, since :
a=[0 0 1 0 1 -1]

a =

     0 0 1 0 1 -1

>> count(a)

c =

     3

but

a= [1 0 0 ; 0 -1 -1; 0 0 0]

a =

     1 0 0
     0 -1 -1
     0 0 0

>> count(a)

c =

     1


I believe the script is only checking the 1st row and after incrementing i , the script is not jumping back up to check the condition for the 1st while loop.

any help will be appreciated

Subject: problem using while loop

From: Roger Stafford

Date: 29 May, 2012 17:39:06

Message: 2 of 3

"H Hachem" <hhachem00@gmail.com> wrote in message <jq2vnp$sru$1@newscl01ah.mathworks.com>...
> I have written the following script to compute the amount of nonzero elements in a matrix:
- - - - - - - -
  Your trouble is caused by placing the "j=1" line in the wrong place. It should be located inside the outer while-loop so that j can be reset every time i is incremented. It would be easier to use 'for' instead of 'while' so that i and j could be more easily handled.

  However, there is an easier solution to the whole problem:

 c = sum(mat(:)~=0);

or else

 c = nnz(mat);

Roger Stafford

Subject: problem using while loop

From: H Hachem

Date: 30 May, 2012 00:06:06

Message: 3 of 3

"Roger Stafford" wrote in message <jq31jq$712$1@newscl01ah.mathworks.com>...
> "H Hachem" <hhachem00@gmail.com> wrote in message <jq2vnp$sru$1@newscl01ah.mathworks.com>...
> > I have written the following script to compute the amount of nonzero elements in a matrix:
> - - - - - - - -
> Your trouble is caused by placing the "j=1" line in the wrong place. It should be located inside the outer while-loop so that j can be reset every time i is incremented. It would be easier to use 'for' instead of 'while' so that i and j could be more easily handled.
>
> However, there is an easier solution to the whole problem:
>
> c = sum(mat(:)~=0);
>
> or else
>
> c = nnz(mat);
>
> Roger Stafford

Thanl you Roger, your post has solved my problem.

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