6

I was doing the following

for i = 1:m,
    index = 0;
    for j = 1:n,
        index = index+values(i,j)*2^(j-1);
        if (j==1)
            symbol_chip = chip_values(index+1,:);
        else
            symbol_chip = [symbol_chip chip_values(index+1,:)];
        end
    end
end

it tells me the following:

symbol_chip might be growing inside the loop. Consider preallocating for speed.

Any ideas?

Alessandro Cuttin
  • 3,822
  • 1
  • 30
  • 36
kl.
  • 361
  • 3
  • 7
  • 15
  • 3
    To avoid repetition, in a related question: http://stackoverflow.com/questions/1548116/matrix-of-unknown-length-in-matlab/1549094#1549094 , I showed a way that improves performance by pre-allocating memory while still being efficient in terms of space by adding more memory space when needed – Amro Jan 28 '10 at 02:43
  • 2
    Have you ever tried Matlab Help??? Just press F1 in any Matlab Window, type 'preallocation' in search edit feld and press ENTER. You will get exactly what you need!!! – Mikhail Poda Jan 28 '10 at 07:48
  • 3
    Just a comment: it is best [not to use `i` and `j` as variable names in Matlab](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab). – Shai Jun 18 '13 at 05:24

2 Answers2

10

Yes. Each time you go around, your elseif block is resizing symbol_chip, which is expensive. Instead, rewrite your code so that you have (say) symbol_chip = zeros(max_size, 1); before the loop. Then, change the contents but not the size of symbol_chip.

You'll need to slightly change your approach, but it will be much faster if you do. If you're not annoyed by the current speed, don't change anything!

Peter
  • 127,331
  • 53
  • 180
  • 211
  • sorry i corrected it should read else not elseif – kl. Jan 28 '10 at 01:18
  • let's say before the outer for loop i put the symbol_chip = zeros(m*32,1); then how would i change my if-else statement? – kl. Jan 28 '10 at 01:19
2

M-Lint will throw this warning if you have a variable that grows inside a loop without being preallocated. You can remove this error by pre-allocating the collection variable.

For instance, if you knew that the variable symbol_chip would have at most i*j elements, you could preallocate it with the statement:

symbol_chip = zeros(i*j);

However, for most applications preallocation will only have a negligible effect on algorithm performance. I would only worry about it if you are dealing with very large data sets.

kamaci
  • 72,915
  • 69
  • 228
  • 366
Andrew Aarestad
  • 1,120
  • 2
  • 11
  • 15
  • 1
    zeros(i*j) will create a 2D array with i*j rows and i*j columns. To fix this use zeros(i*j,1) – George Jan 28 '10 at 02:28