lakshmen
lakshmen

Reputation: 29094

How to detect a sign change for elements in array in Matlab

I have an array of numbers and the numbers change sign. I would like to find the index that there is sign change. How do I do that in Matlab? Is there any shortcut?

Upvotes: 0

Views: 7941

Answers (2)

RTL
RTL

Reputation: 3587

Operating along only one dimension

(eg for rows dim=2)

temp=diff(sign(Array),1,dim)
  • 0 if signs were the same
  • -2 if it went from pos to neg
  • 2 if it went from neg to pos
  • -1 if it went from pos to 0
  • 1 if it went from neg to 0

so the indices of the sign changes can be given by the non zeros,

zeroCrossings=find(temp)

or for row and column indicies

[zC_row,zC_col]=find(temp)

notes: returns indices of elements immediately before a change

Upvotes: 2

Divakar
Divakar

Reputation: 221744

Considering zero is a sign change from both a positive and negative number, you may use this -

%%// Given input
a = randi(10,1,12)-5

%%// Indices where sign change occurs
indices = find([0 diff(sign(a))]~=0)

Output -

a =

    -4     0    -3     5     3     1     0    -4     2    -4    -4     1


indices =

     2     3     4     7     8     9    10    12

Upvotes: 4

Related Questions