### Highlights from FIND for n-D: Find indices and values of nonzero elements in n-D matrix

Be the first to rate this file! 3 Downloads (last 30 days) File Size: 971 Bytes File ID: #23360 Version: 1.0

# FIND for n-D: Find indices and values of nonzero elements in n-D matrix

### H. Brian Hui (view profile)

FINDN is the FIND function for n-D matrix

File Information
Description

Just like the FIND function in Matlab, FINDN is a simple function which will find the indices and values of nonzero elements in a n-D matrix

function [sub v] = findn(A)
% INPUT: A: n-D matrix
% OUTPUT: sub: the k x n index matrix (k is the number of the nonzeros)
v: a column or row vector v of the nonzero entries in A
USAGE:
[sub ] = findn(A)

TESTING CODE:

A = zeros(4,3,5,7);
A(4,2,1,4)=1;
A(2,3,4,6)=2;
A(1,2,3,4)=3;
findn(A)

AUTHOR:
Brian H. Hui (brianhui@alumni.usc.edu)
PhD candidate, Electrical Engineering, University of Southern California

MATLAB release MATLAB 7.6 (R2008a)
08 Jul 2009 Hafsa Qureshi

### Hafsa Qureshi (view profile)

I was trying something like x{1:length(L)}= ind2sub(L,IDX); but it gave error....thanks for posting the code. Still I wonder why my stat didn't work

Comment only
19 Mar 2009 us

### us (view profile)

now, since others have backed-up my idea, you should soon come-up with an updated version...
us

Comment only
19 Mar 2009 H. Brian Hui

### H. Brian Hui (view profile)

Thanks Matt. Did not realize ind2sub can return n subscript arrays.

Comment only
19 Mar 2009 Matt Fig

### Matt Fig (view profile)

This seems a little faster for large number of dimensions:

IDX = find(A);
L = size(A);
[x{1:length(L)}] = ind2sub(L,IDX);
sub = [x{:}];
if nargout==2
v = A(IDX);
end

Something to consider.

Comment only
19 Mar 2009 us

### us (view profile)

why not simply

% the data
a=zeros(2,3,4,5,6);
a(1,1,1,1,1)=1;
a(2,2,2,2,2)=2;
a(1,2,3,4,5)=3;
% the engine (in a function)
[ind{1:ndims(a)}]=ind2sub(size(a),find(a));
ind=cat(2,ind{:});
% the result
disp(ind)
%{
1 1 1 1 1
2 2 2 2 2
1 2 3 4 5
%}

just a thought...
us

Comment only