how do i create a matrix that is 5x5, has eye(3) and then columns 4 and 5 have 2. also the last 2 rows of the matrix are 3s in matlab in one line of code in matlab

You can create the matrix in one line of code using the following MATLAB expression:

main.m
M = [eye(3), repmat([2;2], 1, 2); repmat(3, 2, 5)];
52 chars
2 lines

Explanation:

  • eye(3) creates a 3x3 identity matrix.
  • repmat([2;2], 1, 2) creates a 2-element column vector [2;2] and replicates it horizontally twice to create a 2x2 matrix [2, 2; 2, 2].
  • repmat(3, 2, 5) creates a 2x5 matrix where all elements are equal to 3.
  • Putting it all together using square brackets [] concatenates the matrices vertically.

The resulting matrix M will be a 5x5 matrix with eye(3) as the first three columns, columns 4 and 5 filled with 2's, and the last two rows filled with 3's.

related categories

gistlibby LogSnag