user2441536
user2441536

Reputation: 55

Matlab compare elements of a big Matrix

I have a big Matrix with the size (1000,1000,20)

I have to compare the elements at Position (x,y,1) with (x,y,2) and (x,y,3) and so on till (x,y,20) to find the minimum, and the index where the minimum is.

In the end I want 2 new matrices with size (1000,1000,1): one with the minimum Element, and one with the index where the minimum was.

For example I have:

A(:,:,1)=[1,2;2,4]

A(:,:,2)=[0,3;1,2]

I want to get the matrices:

X = [0,2;2,4]

and:

Y=[2,1;1,1] 

with the index information.

I can solve it with a loop, but would like to use a more time efficient method.

Upvotes: 0

Views: 604

Answers (2)

Dirk
Dirk

Reputation: 10958

You can use the min function for this.

When used in this way:

[C, I] = min(A, [], dim)

it returns the smallest elements along the given dimension dim in C and their indices in I.

The returned indices are linear indices, which you can turn into subscripts using ind2sub for each index.

Upvotes: 0

Rasman
Rasman

Reputation: 5359

I think your example needs to be rewritten, but the built-in min function will do the trick:

[C,I] = min(A,[],3)

Upvotes: 0

Related Questions