user1218247
user1218247

Reputation:

Is there a way to vectorize the use of squeeze in Matlab?

I am currently using squeeze to remove two singleton dimensions from a matrix. The matrix is a large 4d matrix M(:,:,:,:). The first two dimensions are row and column coordinates (y and x). The variable in the third dimension (indexes) selects several values in the third dimension of M.

In a for-loop i am running, matrix M is adressed as M(y,x,indexes,:), which makes the first two dimensions singleton dimensions. These dimensions are then removed with squeeze for use in pdist, like so:

pdist(squeeze(M(y,x,indexes,:)))

Can i vectorize the use of squeeze in this case? (It takes up a lot of time in the loop)

Upvotes: 4

Views: 2337

Answers (2)

Jamie Grant
Jamie Grant

Reputation: 11

For this type of problem using reshape is often a massive improvement on squeeze. I had a issue where squeeze was taking about half the time it took to run a function. Using the profiler I could see squeeze doing a number of unnecessary checks. Using reshape reduced the time for the same operation to 15% of the original time required.

Upvotes: 1

yuk
yuk

Reputation: 19870

If matrix M is not changed inside the loop, a simple solution is to reorder the matrix dimensions with PERMUTE before running for-loop:

Mperm = permute(M,[3 4 1 2]);

Then you can address Mperm instead of M as Mperm(:,:,y,x).

Upvotes: 5

Related Questions