2

In each iteration, I am inserting one row into a matrix whose row number is predetermined. My current implementation is

seqToBePutIntoMatrix = [1 2 3 4 5 6 7 8 9];
col_no = 3; % hence the matrix is 3x3
myMatrix = [];
for i = 1:col_no:length(seqToBePutIntoMatrix)
    myMatrix = [myMatrix; seqToBePutIntoMatrix(i:i+col_no-1)];
end

MATLAB is suggesting me that

The variable myMatrix appears to change size in every loop iteration. Consider preallocation for speed.

I am seriously considering its advice, and wish to preallocate such a 3-row empty matrix and insert one row in each iteration. I have tried this:

seqToBePutIntoMatrix = [1 2 3 4 5 6 7 8 9];
col_no = 3; % hence the matrix is 3x3
myMatrix = [];
j = 1;
for i = 1:col_no:length(seqToBePutIntoMatrix)
    myMatrix(j) = seqToBePutIntoMatrix(i:i+col_no-1);
    j = j+1;
end

However, this is not working. How may I make it work?

Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174
  • 2
    It's a good thing you considered Matlab's advice, [here](http://stackoverflow.com/questions/21023171/variable-appears-to-change-size-on-every-loop-iteration-what)'s a short thread explaining why. – Shai Mar 13 '14 at 17:44

2 Answers2

4

The subscripts myMatrix(j) references only a single element of myMatrix. In order to reference an entire row, you need

myMatrix(j,:) = seqToBePutIntoMatrix(i:i+col_no-1);

Moreover, you need to pre-allocate a 3-by-3 matrix before you start the for-loop

myMatrix = zeros(3,3);

PS,
It is best not to use i and j as variable names in Matlab.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
3

You are still initiallizing myMatrix to an empty matrix (third line):

myMatrix = [];

To preallocate, you should initiallize the matrix to its final size:

myMatrix = NaN(3,3); %// or zeros(3,3), or ones(3,3), or ...

and then, within the loop, fill each row:

myMatrix(j,:) = seqToBePutIntoMatrix(i:i+col_no-1);
Shai
  • 111,146
  • 38
  • 238
  • 371
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147