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

find non-zero elements in N-D array

• Email
• 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;

find(a) gives the answer: 5

Is there a way to get the answer: [1 2 1 1] ??
```
 0
Reply Juliette 12/29/2009 4:32:02 AM

See related articles to this posting

```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
Reply ImageAnalyst 12/29/2009 4:53:50 AM

```"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
Reply Matt 12/29/2009 1:35:05 PM

```Thanks ImageAnalyst!
That was very helpful!

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
Reply us 12/30/2009 3:22:02 PM

4 Replies
542 Views

Similar Articles

12/6/2013 3:52:19 AM
[PageSpeed]