How to return matrix in Matlab using codegen with no c++ memory allocation?

2 ビュー (過去 30 日間)
I do not want any dynamic memory allocation to be done in the C++ codegen. Here is the relevant Matlab code:
% Calculate cross-correlation matrix from a set of vectors (whose length
% can vary from one call to another). All 4 channels will have the length.
function [R] = xcorr_matrix(ch0,ch1,ch2,ch3,channelCount)
% channelCount is 2 or 4
% R is either 2x2 or 4x4 complex double matrix.
% ch0 ... ch3 are complex single vectors.
N = int32(size(ch0,1));
% Convert ch0, ..., ch3 to complex double
x_in = coder.nullcopy(complex(zeros(N,channelCount,'double')));
switch channelCount
case 2
x_in(1:N,1) = ch0(1:N);
x_in(1:N,2) = ch1(1:N);
case 4
x_in(1:N,1) = ch0(1:N);
x_in(1:N,2) = ch1(1:N);
x_in(1:N,3) = ch2(1:N);
x_in(1:N,4) = ch3(1:N);
end
R = (x_in' * x_in); % Compute cross-correlation matrix
Here is the C++ codegen result:
void xcorr_matrix(const creal32_T ch0_data[], const int ch0_size[1], % all the 4 ch_size will be the same value
const creal32_T ch1_data[], const int ch1_size[1],
const creal32_T ch2_data[], const int ch2_size[1],
const creal32_T ch3_data[], const int ch3_size[1],
int channelCount,
::coder::array<creal_T, 2U> &R)
{
::coder::array<creal_T, 2U> x_in;
R.set_size(channelCount, channelCount);
x_in.set_size(N, channelCount);
...
}
I think I can eliminate the x_in.set_size by not using x_in, and replace the matrix multiply with nested for-loops and using double casting; but am unsure how to define R (either 2x2 or 4x4) so as to remove the R.set_size allocations.
One idea I had was to try making R a fixed length 16 element vector, and just use 4 elements for the 2x2 R, and all 16 for the 4x4 R. Would be nicer to be able to use two indices for rows and columns.
Thanks in advance for your help.
Paul
  1 件のコメント
Paul Hoffrichter
Paul Hoffrichter 2024 年 8 月 8 日
編集済み: Paul Hoffrichter 2024 年 8 月 8 日
Looking at other projects, I am seeing a number of coder::array uses. Does this mean there is dynamic memory allocations there as well? For example:
const ::coder::array<float, 1U> &x
or
::coder::array<float, 1U> m0;

サインインしてコメントする。

採用された回答

Paul Hoffrichter
Paul Hoffrichter 2024 年 8 月 8 日
Originally, R was using the coder.nullcopy since R = (x_in' * x_in) would fill in the values.
I did remove x_in which eliminated the x_in.set_size.
I set R to zeros: R = complex(zeros(channelCount,channelCount,'double'));
Replaced the matrix multiply
R = (x_in' * x_in); % Compute cross-correlation matrix
with a triple summation (row, column, number of samples).
These steps eliminated ::coder::array from this algorithm.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB Coder についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by