Converting coder::array<unsigned char, 3U> to unsigned char
Show older comments
I am using Matlab coder to generate c++ codes for a script i have made. The output datatype of MATLAB coder is coder::array<unsigned char, 3U>. Would you please help me figure out how to convert this into unsigned char so that i can use it in opencv.
Thank you
1 Comment
Alexander Bottema
on 24 Aug 2022
To directly access the underying data of a coder::array you can use the ".data()" method. The total number of elements can be computed via the ".numel()" method. Size of each dimension is available via the ".size(dimension)" method.
I attached a full example (see example.zip).
example.m:
function y = example(n)
y = zeros(n,n,n,'uint8');
for i = 1:numel(y)
y(i) = 64 + i;
end
main.cpp:
#include <iostream>
#include "example.h"
#include "coder_array.h"
int main(int argc, char **argv[])
{
(void)argc;
(void)argv;
coder::array<unsigned char, 3U> out;
example(2, out);
int n = out.numel();
unsigned char *data = out.data();
for (int i = 0; i < n; i++) {
std::cout << data[i];
}
std::cout << std::endl;
return 0;
}
doit.m:
cfg = coder.config('exe');
cfg.TargetLang = 'C++';
codegen -args 0 -config cfg example main.cpp
And running the executable gives:
>> !example (!./example on Linux)
ABCDEFGH
Answers (1)
Anirban Ghosh
on 24 Aug 2022
2 votes
Hi Abhijith,
Please refer to this documentation page for information on using the coder:array template: Use Dynamically Allocated C++ Arrays in Generated Function Interfaces. In particular, note the "Using the coder::array Class Template" section and the two examples that follow.
If your output (say myArray) is of type coder::array<unsigned char, 3U>, it contains elements of type unsigned char and has 3 dimensions.
- To access the sizes of the three dimensions, call the size method: myArray.size(0), myArray.size(1), and myArray.size(2).
- To access the (i,j,k)-th element of myArray, call the at method: myArray.at(i,j,k). This call will return the unsigned char value stored at that location.
- In your code, you can pre-allocate an unsigned char array and populate it with these values.
1 Comment
xingxingcui
on 23 Feb 2023
Edited: xingxingcui
on 23 Feb 2023
How should I set the data elements of coder::array if the other way around?(Instead of copying element by element, the in-place method), I'm following the linked documentation and trying myself, but unfortunately I couldn't make it work!
Categories
Find more on Function Definition in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!