Why does is take so long to add elements to an mwArray?

1 view (last 30 days)
The following code will illustrate this behavior:
#include "matlab.hpp"
#include <stdlib.h> /* used for EXIT_SUCCESS */
#ifdef GCC
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
#endif
int main(void)
{
#ifdef EXCEPTIONS_WORK
try
#endif
{
mwArray a, b, c, x, y, z;
// x = rand(4,4);
//y = magic(7);
//z = eig(x);
for( int i=1; i<30000;i++)
{
x(i)=i;
y(i)=i;
z(i)=i;
//if (i%10000==0) cout<<i<<endl;
}
// Save (and name) the variables
save("ex5.mat", "x", x, "y", y, "z", z);
// Load the named variables
load("ex5.mat", "x", &a, "y", &b, "z", &c);
// Check to be sure the variables are equal
if (tobool(a == x) && tobool(b == y) && tobool(c == z))
{
cout << "Success: all variables equal" << endl;
}
else
{
cout << "Failure: loaded values not equal to saved values" << endl;
}
}
#ifdef EXCEPTIONS_WORK
catch (mwException &ex)
{
cout << ex;
}
#endif
return(EXIT_SUCCESS);
}
Testing this example for different values of i yielded the following results. For 300 elements the execution time was .32 seconds; for 3,000 elements it was 2.173 seconds; and for 30,000 elements it was 388 seconds. The execution time seems to be growing exponentially.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
The problem is that when you use indexing to expand an array, the library has to reallocate the array before adding the new element. This reallocation takes more time as the array gets larger.
The solution is to preallocate the array before assigning into it. In the previous example, if you add the lines
x = zeros(30000);
y = zeros(30000);
z = zeros(30000);
before the loop, you should see much better performance.
This also applies to vector augmenting in MATLAB; it is not specific to the C/C++ Math Library.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!