tags:

views:

63

answers:

3

Why create a matrix of 0's in Matlab? For example,

A=zeros(5,5);
for i = 1:5
  A(i)=exp(i);
end
+1  A: 

This is identical to asking: Why create a variable with value 0?

Usually you would do this if you plan to accumulate a bunch of results together somehow. In this case, you have to start "somewhere".

j_random_hacker
+6  A: 

Following on from j_random_hacker's answer, it's much more efficient in MATLAB to pre-allocate an array rather than letting MATLAB expand it. MATLAB can expand arrays if you simply assign elements off the current "end" of the array, like so:

x = []
for ii=1:1e4
  x(ii) = 1/ii;
end

That's really inefficient because at each step in the loop, MATLAB will re-allocate "x" to be one element larger than it was previously. The following is much faster:

x = zeros( 1, 1e4 );
for ii=1:1e4
  x(ii) = 1/ii;
end

(Probably fastest still in this case is: x = 1./(1:1e4);, but the pre-allocation route is what you need when you can't resolve things to a vectorised operation)

Edric
It should be noted that this kind of optimization, while always helpful is not usually significant until big matrices are involved. Make a little test script to see how this effect scales. I personally do not worry about this until about 200+ elements in a growing vector.
MatlabDoug
Yep, growing small arrays is (relatively) fine, that's why I chose 1e4 elements ;)
Edric
A: 

Although it is possible to start out with an empty matrix and expand it by concatenating (adding) new elements, vector extension is highly inefficient in MATLAB because it requires new memory every time another element is concatenated. Preallocation establishes a matrix that's the right size in advance, then each zero element can be replaced with the correct value. This method is much more efficient, especially in programs involving looping.

related questions