error using horzcat dimensions of arrays being concatenated are not consistent. in matlab

This error occurs when you try to concatenate two arrays that have different sizes along a particular dimension. For instance, consider the following example:

main.m
A = [1 2 3];
B = [4 5];
C = [A B];
35 chars
4 lines

Here, A has size 1x3, and B has size 1x2. Therefore, the concatenation operation fails with the error "Error using horzcat. Dimensions of arrays being concatenated are not consistent."

To fix this error, make sure that the arrays you are trying to concatenate have the same size along the relevant dimension. In the example above, you could fix the error by transposing either A or B (so that they have the same orientation), and then concatenating them along the vertical dimension:

main.m
A = [1 2 3];
B = [4 5];
C = [A; B];
36 chars
4 lines

Here, C will be a 2x3 matrix:

main.m
C = 

     1     2     3
     4     5     0
44 chars
5 lines

Note that the missing element in C is filled with a 0, since B has only two elements. If you want to account for this, you may need to pad B with an appropriate number of zeroes before concatenating it with A.

If you still encounter the error after trying the above fix, check that all the arrays in your code have the same size along the relevant dimension.

related categories

gistlibby LogSnag