how to add first row to to a matrix in matlab

To add the first row to a matrix in Matlab, you can use the following code:

main.m
% create a row vector to add as the first row
newRow = [1 2 3];

% create a matrix
oldMatrix = [4 5 6; 7 8 9];

% concatenate the row vector and the old matrix along the vertical dimension
newMatrix = [newRow; oldMatrix];
222 chars
9 lines

In this example, I created a row vector called newRow with the values [1 2 3]. Then, I created an original matrix called oldMatrix with the values:

main.m
   4     5     6
   7     8     9
34 chars
3 lines

To add the newRow vector as the first row of the oldMatrix, I used the vertcat function (represented by the square bracket notation [ ]) to concatenate newRow above the oldMatrix, resulting in:

main.m
   1     2     3
   4     5     6
   7     8     9
51 chars
4 lines

This new matrix is stored in the newMatrix variable.

related categories

gistlibby LogSnag