Code covered by the BSD License

### Highlights from Vectorized FIND with 'FIRST' option

5.0

5.0 | 4 ratings Rate this file 17 Downloads (last 30 days) File Size: 5.13 KB File ID: #24641

# Vectorized FIND with 'FIRST' option

05 Jul 2009 (Updated )

Find the first non-zero element(s) along row/column - or any other dimension

File Information
Description

Up to now, to find the first non-zero element of a matrix along a column (for example) user might:

1. Use for-loop with FIND command
for j=1:size(A,2)
... = find(A(:,j), 1, 'first');
end

2. Use other vectorized methods, often time not very straight-forwards (MAX, LOGICAL, SPARSE, etc...). This method creates temporary arrays and scan such the arrays few times while doing some calculation.

3. Write the basic FOR-LOOP algorithm to accomplish the task.

The FINDFIRST command does just the same, but implemented using MEX engine which should be faster than any of the above. It can handle 'FIRST', 'LAST' option, and return more than one FIND count.

NOTE: not yet tested on Linux (gcc)

MATLAB release MATLAB 7.8 (R2009a)
Other requirements Mex setup
01 Nov 2013

I have tried this:

M = 1000; N = 20000;
A = rand(M, N) < 0.5;
tic, B = findfirst(A, 1, M); toc
tic
C = zeros(M, N);
inds = zeros(N, 1);
for hh = 1:N
tmp = find(A(:,hh));
inds(hh) = numel(tmp);
C((hh - 1) * M + (1:inds(hh))) = tmp;
end
toc
all(B(:) == C(:))

Works fine.

01 Nov 2013
26 Sep 2013

Your comment is incorrect, on the 7th line should be:
B=zeros(1,size(A,2));

22 Aug 2013

For this to work on linux, the typedefs need to be changed on lines 38-41 from:

typedef long long int int64;
typedef long int int32;
typedef short int16;
typedef char int08;

to:

typedef int64_t int64;
typedef int32_t int32;
typedef int16_t int16;
typedef int8_t int08;

best,
David

22 Aug 2013
17 Apr 2010
17 Apr 2010

handy and fast ! it implemnts an option not available in the standard matlab find function