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:
Determine zero elements in a matrix

Subject: Determine zero elements in a matrix

From: Jess J

Date: 10 Dec, 2009 09:32:19

Message: 1 of 3

Hi, here is my question.

If i ve a matrix i.e. A = [p q r s t u] = [1 4 0 3 5 0] (the real matrix size is much bigger), how can i determine the zero elements so that i can have something like this:

if r = 0 then *action carry out*

Thanks in advance.

Regards,
Jess

Subject: Determine zero elements in a matrix

From: Jos (10584)

Date: 10 Dec, 2009 09:40:17

Message: 2 of 3

"Jess J" <jessie_jtl@yahoo.co.uk> wrote in message <hfqf73$it3$1@fred.mathworks.com>...
> Hi, here is my question.
>
> If i ve a matrix i.e. A = [p q r s t u] = [1 4 0 3 5 0] (the real matrix size is much bigger), how can i determine the zero elements so that i can have something like this:
>
> if r = 0 then *action carry out*
>
> Thanks in advance.
>
> Regards,
> Jess

Something like this?

A = [1 4 0 3 5 0] ;
tf = A==0 ; % create a logical vector
idx = 3 ;

if tf(idx),
   disp(['Element at position ' num2str(idx) ' is zero.']) ;
else
  disp(['Element at position ' num2str(idx) ' is NOT zero.']) ;
end

allidx = find(tf) % all indices where tf is true, i.e., where A is zero

hth
Jos

Subject: Determine zero elements in a matrix

From: John D'Errico

Date: 10 Dec, 2009 09:48:01

Message: 3 of 3

"Jess J" <jessie_jtl@yahoo.co.uk> wrote in message <hfqf73$it3$1@fred.mathworks.com>...
> Hi, here is my question.
>
> If i ve a matrix i.e. A = [p q r s t u] = [1 4 0 3 5 0] (the real matrix size is much bigger), how can i determine the zero elements so that i can have something like this:
>
> if r = 0 then *action carry out*

Do you wish to do something if ANY element is zero?
Then use any.

   any(r == 0)

or even

   any(~r)

So your code might look like...

   if any(~r)
      error('The sky is falling!')
   end

Do you wish to locate the zero elements and then
process them separately? Is this operation something
that you can do in one operation? Then try this...

   ind = find(r == 0);
   if ~isempty(ind)
     stuff
   end

Learn to use tests like these shown, along with
vectorized operations to make your code efficient.

John

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