How to convert matrix or vector in Matlab workspace into C/C++ array usable in ".c" file?

11 views (last 30 days)
I have 1*1050 duble vector (a) in my workspace. I want use this array in a ".c" file. How can this conversion?
For example my matlab array is:
a = [1 2 3 4 5];
I want convert this vector into:
uint16_t a[5] = {1,2,3,4,5}
usable in ".c" file.

Answers (1)

dpb
dpb on 3 Apr 2023
Edited: dpb on 3 Apr 2023
a=1:5;
vname='a';
precision=16;
fmt=['uint%d_t %s={' repmat('%d,',1,numel(a)-1) '%d}'];
c_code=sprintf(fmt,precision,vname,a)
c_code = 'uint16_t a={1,2,3,4,5}'
You can get more clever about finding the variable name of the array instead of hardcoding it by wrapping the above in a function that can query the passed in variable name and can obviously also make the type of the output variable user-settable as well as the precision, etc., etc., etc., ...
If the array gets to be large as in your initial question, you'll need to look at possible compiler limits on length of source line and do things to get around that kind of secondary issues...
  1 Comment
dpb
dpb on 3 Apr 2023
Oh. Above format automagically allocates to the size of the given array; if it is wanted/needed to set an array size and only allocate M out of N elements just introduce the '[%d]' into the format string and add the N value into the argument list...
a=1:5;
vname='a';
precision=16;
N=10;
fmt=['uint%d_t %s[%d]={' repmat('%d,',1,numel(a)-1) '%d}'];
c_code=sprintf(fmt,precision,vname,N,a)
c_code = 'uint16_t a[10]={1,2,3,4,5}'
which would create an array of 10 elements with the last 5 being zero-filled by the compiler.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!