why is there a horzcat error with this x = [eye(3),2*ones(2,3);3*ones(2,5)] in matlab

The reason for the horzcat error when using the expression x = [eye(3),2*ones(2,3);3*ones(2,5)] in MATLAB is that the matrices you are trying to concatenate horizontally have different number of rows.

In this case, the eye(3) matrix has 3 rows and the matrix 2*ones(2,3);3*ones(2,5) has 4 rows. MATLAB requires that all matrices being concatenated horizontally have the same number of rows.

To fix this error and make the concatenation work, you need to adjust the dimensions of the matrices so that they have the same number of rows.

For example, if you want to maintain the number of rows in the second matrix and repeat the last row of the first matrix, you can modify the expression to:

main.m
x = [eye(3); repmat(eye(3)(end,:), 2, 1), 2*ones(2,3);3*ones(2,5)];
68 chars
2 lines

This will concatenate the matrices vertically using the semicolon (;) operator and repeat the last row of the first matrix using the repmat function.

related categories

gistlibby LogSnag