Matlab - insert/append rows into matrix iteratively

泪湿孤枕 提交于 2019-12-05 02:43:35

m = [m ; new_row]; in your loop. If you know the total row number already, define m=zeros(row_num,column_num);, then in your loop m(i,:) = new_row;

Luis Mendo

Just use

m = [m; row];

Take into account that extending a matrix is slow, as it involves memory reallocation. It's better to preallocate the matrix to its full size,

m = NaN(numRows,numCols);

and then fill the row values at each iteration:

m(ii,:) = row;

Also, it's better not to use i as a variable name, because by default it represents the imaginary unit (that's why I'm using ii here as iteration index).

To create and add a value into the matrix you can do this and can make a complete matrix like yours. Here row = 5 and then column = 3 and for hence two for loop.

Put the value in M(i, j) location and it will insert the value in the matrix

for i=1:5
    for j=1:3
        M(i, j) = input('Enter a value = ')
    end
    fprintf('Row %d inserted successfully\n', i)
end

disp('Full Matrix is = ')
disp(M)

Provably if you enter the same values given, the output will be like yours,

Full Matrix is = 
1 2 3
3 2 1
1 2 3
4 3 2
1 1 1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!