Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

One liner to re-size two matrices to the same size as the smaller matrix

Say i have two matrices: A and B and they are two different sizes. For eg:

A = [1 2]

B = [3 4 5]

What i want to do is crop the matrix that is bigger and remove any elements. ie. in the above case you would have:

A = [1 2] <- Stays the same because it's smaller

B = [3 4] <- Cropped to same size as A.

Now i could do it so easily with a bunch of boring if and else statements but i was hoping a wizard or witch would help me uncover the magic matlab syntax that will do this in one line.

Assume that they are always 3xN ie. vectors.

Upvotes: 0

Views: 75

Answers (2)

R&#233;mi
R&#233;mi

Reputation: 527

This should work on multi-dim matrix too, basically the same as Jonas answer.

d = min([size(A); size(B)]);
A = A(1:d(1),1:d(2));
B = B(1:d(1),1:d(2));

I wonder how a size matrix (like [2 4]) can be transformed into index ie [1:2, 1:4])...

Upvotes: 2

Jonas
Jonas

Reputation: 74930

If the size only differs along the second dimension, you can crop the arrays like this:

colA = size(A,2);
colB = size(B,2);

A = A(:,1:min(colA,colB))
B = B(:,1:min(colA,colB))

Upvotes: 2

Related Questions