COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### find non-zero elements in N-D array

• Follow

```In the matlab documentation, it says:

" [row col] = find(X)
If X is an N-dimensional array with N > 2, col contains linear indices for the columns "

Is there an easy way to extract the actual indices instead of the 'linear indices' ??

In
a=zeros(4,4,4,4); a(1,2,1,1)=1;

Is there a way to get the answer: [1 2 1 1] ??
```
 0

```Juliette:
Not with one function call, that I know of - you need two.
You need to follow up the call to find with a call to ind2sub().
Like this:

workspace; % Display workspace panel.
a=zeros(4,4,4,4);
a(1,2,1,1)=1;
linearIndexes = find(a ~= 0)
% Get the index in each of the 4 dimensions.
[d1 d2 d3 d4] = ind2sub(size(a), linearIndexes)

Output:
linearIndexes =
5

d1 =
1

d2 =
2

d3 =
1

d4 =
1

Regards,
ImageAnalyst
```
 0

```"Juliette Salexa" <juliette.physicist@gmail.com> wrote in message <hhc0o2\$rs0\$1@fred.mathworks.com>...
> In the matlab documentation, it says:
>
> " [row col] = find(X)
> If X is an N-dimensional array with N > 2, col contains linear indices for the columns "
>
> Is there an easy way to extract the actual indices instead of the 'linear indices' ??
>
> In
> a=zeros(4,4,4,4); a(1,2,1,1)=1;
>
> find(a) gives the answer: 5
>
> Is there a way to get the answer: [1 2 1 1] ??

ImageAnalyst gave the solution, but I have to ask. Are you sure you need this?

Typically, in MATLAB, you can accomplish most things with linear indices just as well as with"actual" indices, and with less computational effort. You can often even accomplish them without any indices at all.
```
 0

```Thanks ImageAnalyst!

Matt J,
I simply needed to see the indices (not use them for anything).

Cheers,
```
 0
Reply juliette.physicist (183) 12/30/2009 3:30:08 AM

```ImageAnalyst <imageanalyst@mailinator.com> wrote in message <3554c0f2-b908-4197-9f06-7ed12e5771d7@r24g2000yqd.googlegroups.com>...
> Juliette:
> Not with one function call, that I know of - you need two.
> You need to follow up the call to find with a call to ind2sub().
> Like this:
>
> workspace; % Display workspace panel.
> a=zeros(4,4,4,4);
> a(1,2,1,1)=1;
> linearIndexes = find(a ~= 0)
> % Get the index in each of the 4 dimensions.
> [d1 d2 d3 d4] = ind2sub(size(a), linearIndexes)

just a minor change towards versatility...

a=zeros(4,4,4,4);
a(1,4,2:3,3)=1;
lix=find(a);
clear r;
[r{1:ndims(a)}]=ind2sub(size(a),lix);
r=cat(2,r{:})
%{
%    r =
1     4     2     3
1     4     3     3
%}

us
```
 0

4 Replies
400 Views

Similiar Articles:

7/22/2012 8:26:37 AM