Tuesday, December 31, 2013

Find a value in an array in octave

As intuitive as octave is, the command is find. However, through the standard help spit out by octave it is not very apparent how we can search for a value.

Say we create an array of 10 values rounded off to have numbers between 1 to 10:
octave:27> x = floor(rand(1,10)*10)+1
x =
   7   3   3   4   6   7   6   4   2   6
Now, say we want to find if the array contains the value 3, we would do something like:
octave:28> m = find(x==3, 1)
m =  2
The output m = 2 tells us the index of the location and also the fact that this value is present. If we test for a non-existing value for something like say 10,
octave:29> m = find(x==10, 1)
m = [](1x0)

If you now test for the value of m in an if condition it would indicate false. So for example you could have a line of code which says:
if m
% Do stuff because the number is found.
% Do stuff if the number is absent in the array.
This example can be used to find a value in a matrix or an array in GNU octave.


Post a Comment