trican
trican

Reputation: 1197

Avoiding for-loops in this Matlab matrix operation

I have a large 4 dimensional matrix, and I wish to 1) find the minimum of 2 of those dimensions (i.e. a 4000x4000 result) and then 2) count the number of elements in those last two dimensions that are less than (lets say) 5 times the minimum (i.e giving a result of 4000x4000). I'm a bit stumped as to how to do this without reverting to for loops

Some code might aid my description:

A      = rand([4000,4000,7,7]);
B(:,:) = min(A(:,:,1:7;1:7)); % this isn't quite right?
C      = size( A < 5*B ) % obviously totally wrong

any pointers would be great - many thanks!

Upvotes: 0

Views: 541

Answers (2)

Amro
Amro

Reputation: 124563

If I understood this correctly, the following should do the job:

mn = min(min(A,[],3),[],4);
num = sum(sum(bsxfun(@lt, A, 5*mn),3),4)

Upvotes: 2

Foo Bah
Foo Bah

Reputation: 26251

First, it should be rand([4000,4000,7,7])

Second, to use min, you have to do something like min(A, [], 1) (replace 1 with the dimension)

Third, assuming you had A and B, you want C = sum(sum(A < 5*B))

Upvotes: -1

Related Questions