Have your cake?

Eat it, too.

Identifying Integers in MATLAB

Posted by JoeyBreak

A few weeks ago I was putting some MATLAB code together for my image processing project. While I was brainstorming its development, I thought of needing to identify integers within a matrix of values (double type). After not finding any real simple solutions that satisfied me in a brief internet search, I spent a few minutes experimenting and came up with what seems to be a pretty simple solution. I spent extra time turning it into a function getIntegers which will return two variables into the workspace: one for the values that are integers in a matrix and another as the locations or positions of the integers within the matrix.

>> A = magic(5)/3

A =

5.6667 8.0000 0.3333 2.6667 5.0000
7.6667 1.6667 2.3333 4.6667 5.3333
1.3333 2.0000 4.3333 6.6667 7.3333
3.3333 4.0000 6.3333 7.0000 1.0000
3.6667 6.0000 8.3333 0.6667 3.0000

>> [integers, locs] = getIntegers(A)

integers =

0 8 0 0 5
0 0 0 0 0
0 2 0 0 0
0 4 0 7 1
0 6 0 0 3

locs =

1 2
1 5
3 2
4 2
4 4
4 5
5 2
5 5

Looking at the integers matrix, the values that are integers are retained from matrix A and the locations of those integers in A are returned as matrix locs where the first and second columns are the row and column coordinates of each integer respectively. The locs will come in handy should you need to identify where a zero-valued integer was. The function has been tested working for version 7.8.0 (R2009a) for 1-D and 2-D matrices. I've also posted the foundation to this integer solution on a thread at MATLAB Central.

Link to m-file: getIntegers.m

In other fun news, Mark "The Hammer" Shea gives a Catholic perspective about what extra-terrestrial life would mean to Catholicism.


Kyle0101 said...

You're right, that would come in handy!! Those zero-value integers are tough to find. :)

JoeyBreak.com said...

None of those zeros in the integers matrix were a part of the original A matrix. An original 0 integer would be difficult to identify when mixed in with all the other non-integer digits that get reduced to zero (at least when looking at the data) but I imagined that some users would be dealing with very large matrices in which they weren't looking at the data. I wondered if it would be better for the function to return a single row matrix of just the integers without setting non-integers to zero but by also returning the locations of the integers, the end-user would be able to do so with only a few lines of code. Would you think it better for the function to have an extra boolean input to just output a single row matrix of just the integers?