10

How in matlab I can interactively append matrix with rows?

For example lets say I have empty matrix:

m = [];

and when I run the for loop, I get rows that I need to insert into matrix.

For example:

for i=1:5
  row = v - x; % for example getting 1 2 3
  % m.append(row)?
end

so after inserting it should look something like:

m = [
     1 2 3
     3 2 1
     1 2 3
     4 3 2
     1 1 1
]

In most programming languages you can simply append rows into array/matrix. But I find it hard to do it in matlab.

Matias Andina
  • 4,029
  • 4
  • 26
  • 58
Andrius
  • 19,658
  • 37
  • 143
  • 243

3 Answers3

19

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;

lennon310
  • 12,503
  • 11
  • 43
  • 61
  • There is a big difference between `m=[m,x]` and `m(end+1,:)=x` when appending s column. See [this answer](https://stackoverflow.com/a/48990695/7328782). For rows, the difference maybe not as large, I haven’t compared, but it is certainly recommendable to append columns rather than rows, if preallocating a matrix of the right size is not possible. Appending columns can be done without copying data in many cases. – Cris Luengo Nov 12 '18 at 00:20
3

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).

Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • I just used m = NaN(numRows,numCols); as definition outside prior to the loop and then m(row,:) = row; inside the loop. That was it. tks! – Alfredo Rodriguez Nov 05 '19 at 01:51
1

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
Maniruzzaman Akash
  • 4,610
  • 1
  • 37
  • 34