neptune36
neptune36

Reputation: 787

Write to next empty row in matrix in Matlab

I have a rather complicated set of 5 nested for loops that generate a pair of values on each iteration (say x and y) and I'd like to put each pair of values onto a new row in a matrix.

Usually, I would just write something like:

X = zeros(n, 2)

for i = 1:n

X(i, :) = newrow

end

But I'm not sure how this would work with the set of 5 loops. Is it possible to write each new pair of values to the next empty row in a matrix? Currently I'm just starting with a 1x2 matrix and appending a new row on every iteration, but I'd like to avoid this if possible.

Upvotes: 0

Views: 4449

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112779

  1. You can use this within the innermost loop, without preallocating X. Not recommended (see approach 2).

    X(end+1, :) = newrow;
    
  2. A better approach (to avoid memory reallocation) would be to preallocate your matrix to the final size and then index each row using a row counter that you increase witin the innermost loop:

    X = NaN(1000,2); %// for example. "1000" <-- product of number of iterations
    r = 0;
    for ii = 1:10
       for jj = 1:100
           r = r + 1; %// increase row counter
           X(r,:) = newrow;
       end
    end
    

Upvotes: 1

Related Questions