0

I have a Matlab function converted to C++ using Matlab Coder. The input is a single dimensional array of :Infx1 and the output of matlab function is a 2-D array. I initialize this (the output) using

result = zeros(500,18); 

Within my main loop I maintain a variable count that varies from 1 to 500 and before the end of the loop I fill the output array using

result(count,:) = blocks;

where blocks is a 18x1 vector computed in every loop.

In my converted C++ file I expect result to be a 2-D array. But it happens to be a vector with output given by

for (loop_ub = 0; loop_ub < 18; loop_ub++) {
           result[(count + 500 * loop_ub) - 1] = blocks[loop_ub];
        }

The initialization of result can be seen as

memset(&result[0], 0, 9000U * sizeof(real_T));

I cannot figure out the reason why this is not a 2-D array. Any help is highly appreciated.

Thanks

Ryan Livingston
  • 1,898
  • 12
  • 18
suranga
  • 228
  • 1
  • 4
  • 15

1 Answers1

1

All memory is ultimately flat (1-dimensional) and you often get the best performance when interpreting it that way. In this case, a single allocation will do (of size 500*18*sizeof(real_T)) so matlab uses it - you'll get better caching performance due to spatial locality. The code generator could have wrapped the allocation in a multi-dimensional array type (e.g. see this question), but that obscures the fact that each row is actually contiguous in memory, a useful fact to know. Otherwise, for example, it wouldn't be clear that a single memset could be used to initialize the array.

Community
  • 1
  • 1
MooseBoys
  • 6,641
  • 1
  • 19
  • 43