MATLAB Answers


Why does union transpose row vectors when unioned with empty vectors?

Asked by Mike
on 21 Aug 2013

In R2013a, when you do union([],[1 2]) , MATLAB returns a column vector, i.e. [1;2], as opposed to the row vector [1 2] that it returned in prior versions. It is given in the documentation that the index vectors returned by union will now always be column vectors. However, that row vector will now be transposed whenever unioned with a null vector seems like it couldn't possible have a purpose, and at the least should be documented if it was intentional.




No products are associated with this question.

1 Answer

Answer by Walter Roberson
on 21 Aug 2013

Look at

help union

You will find

The behavior of union has changed.  This includes:
    -	occurrence of indices in IA and IB switched from last to first
    -	orientation of vector C
    -	IA and IB will always be column index vectors
    -	tighter restrictions on combinations of classes

So the change in orientation of the union output is documented.


on 21 Aug 2013

OK, you're right, I had missed the relavent statement in the documentation, which says:

"If the 'rows' flag is not specified, then C is a column vector unless both A and B are row vectors."

I understand that one must arbitrary pick a shape when taking a union of a row vector with a column vector, and it seems like MATLAB is just trying to make these arbitrary decisions more consistent across different functions, which is fine. But this behavior is just absurd in the case where A is a null vector. I can't imagine anybody wanting (or expecting) union to do anything but return B as it is (no transposing!) when A is null. This is just going to lead to many annoying bugs and I expect was just a case that was not considered.

Walter Roberson
on 21 Aug 2013

When I use union(), I seldom expect that the output will be the same as the input, as the input is allowed to be unsorted and with duplicates, and the order of the output is not specified by union() other than that it will not have duplicates (in practice it is also sorted.)

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!