简体   繁体   English

在Matlab中正确设置二维数组到C ++的转换

[英]2-dimensional array not set properly in matlab to C++ conversion

I have a Matlab function converted to C++ using Matlab Coder. 我有一个使用Matlab Coder转换为C ++的Matlab函数。 The input is a single dimensional array of :Infx1 and the output of matlab function is a 2-D array. 输入是:Infx1一维数组,而matlab函数的输出是2D数组。 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 在我的主循环中,我维护一个从1到500的可变count ,在循环结束之前,我使用以下命令填充输出数组

result(count,:) = blocks;

where blocks is a 18x1 vector computed in every loop. 其中,block是在每个循环中计算的18x1向量。

In my converted C++ file I expect result to be a 2-D array. 在我转换后的C ++文件中,我期望result是二维数组。 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 result的初始化可以看作是

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 谢谢

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. 在这种情况下,将进行单个分配(大小为500 * 18 * sizeof(real_T)),因此matlab会使用它-由于空间局部性,您将获得更好的缓存性能。 The code generator could have wrapped the allocation in a multi-dimensional array type (eg 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. 否则,例如,不清楚是否可以使用单个内存集来初始化数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM