MATLAB: Either I or matlab is going crazy with vertcat using brackets

matricesvertcat

Someone please point out what is going on with this piece of code. Matlab is running the first 3 concatenations fine, and not the last one. It's driving me crazy. It spits out
Error using vertcat Dimensions of matrices being concatenated are not consistent.
for that line. Please help. Thanks!
e = [1 1 1 1];
vertcat( 2*(e(2)*e(4) - e(3)*e(1)),2*(e(3)*e(4) + e(2)*e(1)),e(4)^2 + e(1)^2 - e(2)^2 -e(3)^2); % calling vertcat works
[ 2*(e(2)*e(4) - e(3)*e(1)) 2*(e(3)*e(4) + e(2)*e(1)) e(4)^2 + e(1)^2 - e(2)^2 -e(3)^2]; % horizontal works
% subing in works
a = 2*(e(2)*e(4) - e(3)*e(1)); b = 2*(e(3)*e(4) + e(2)*e(1)); c = e(4)^2 + e(1)^2 - e(2)^2 -e(3)^2;
[a; b; c]
% but this doesn't work for some reason...
[ 2*(e(2)*e(4) - e(3)*e(1));2*(e(3)*e(4) + e(2)*e(1));e(4)^2 + e(1)^2 - e(2)^2 -e(3)^2];

Best Answer

MATLAB is doing exactly as documented:
"Blank spaces around operators such as -, :, and ( ), are optional, but they can improve readability... However, blank spaces act as delimiters in horizontal concatenation"
Because of this you have unknowingly used horzcat (via []) to generate different length vectors, which then cannot be concatenated together using vertcat. This is trivial to demonstrate, because basically you are doing this:
>> [1+2 2 -3]
ans =
3 2 -3
But I think now you can see why this is not a vector with two values, as you expect it to be. Instead, MATLAB is doing exactly as its documentation states it should. Learn to read the documentation instead of going crazy.
Your first two examples, with vertcat and horzcat are not doing what you think they are. In the case of vertcat because the input arguments are not being concatenated in themselves: they are simply interpreted as operations to be evaluated before being passed to vertcat. It is much as if you did this:
x1 = 2*(e(2)*e(4) - e(3)*e(1));
x2 = 2*(e(3)*e(4) + e(2)*e(1));
x3 = e(4)^2 + e(1)^2 - e(2)^2 -e(3)^2;
vertcat(x1,x2,x3)
because MATLAB already knows that they are input arguments to a function and are not in themselves being concatenated (this only happens inside vertcat). Perhaps what you did not check is the output of these two examples: did you notice that they have different number of terms? The reason should be clear by now.
Summary: learn to read the documentation (this is the best thing any MATLAB learner can do). And never rely on space characters to create vectors or matrices. Although loved by some, using space characters leads to exactly the problems that you see here. Much clearer is to always specify vectors and matrices using commas and semi-colons. Then the code intent is always perfectly clear:
>> [1+2 2 -3] % is this a mistake? Should it be 2-3 ?
ans =
3 2 -3
>> [1+2, 2-3] % comma makes separation clear
ans =
3 -1