Reputation: 228
I am trying to convert a Matlab project into C++ by using Matlab coder. I have few places in my code that I use num2str
function. But when trying to build the project using Matlab coder I get the following error.
"The function 'num2str' is not supported for standalone code generation."
I used this function in cases where I needed to create a field identifier for structs.
Eg:
for i=1:numel(bvec)
fId = ['L', num2str(i)];
tmp = mystruct.(fId);
% do some work here
end
Is there an alternative to the function num2str
for me to be able to convert the project?
Upvotes: 2
Views: 7112
Reputation: 21
I wrote the following code for Matlab2016a Coder to replace num2str, it also supports double precision:
function str = DoubleArray2String(x)
str_cell=cell(1,length(x));
for i=1:length(x)
n = x(i);
l = fix(n);
r = n-l;
str_cell{i} = strjoin({Double2String(l),Reminder2String(r)},'.');
end
str = strjoin(str_cell,',');
end
function str = Double2String(n)
str = '';
while n > 0
d = mod(n,10);
str = [char(48+d), str];
n = (n-d)/10;
end
if isempty(str)
str='0' ;
end
end
function str = Reminder2String(n)
str = '';
while (n > 0) && (n < 1)
n = n*10;
d = fix(n);
str = [str char(48+d)];
n = n-d;
end
if isempty(str)
str='0' ;
end
end
Upvotes: 2
Reputation: 845
A function equivalent of Matlab's num2str
can be written using to_string in C++. Please see my version of the function:
#include"stdafx.h"
#include <sstream>
#include <string.h>
using namespace std;
string num2str(int number)
{
string s;
s = to_string(number);
return s;
}
Upvotes: 0
Reputation: 1769
Using sprintf
would be easy but I'm not sure if you can use it?
fId = sprintf('L%d', i);
If numel(bvec)
is in the range 0 to 9 you could use char
:
fId = ['L', char(48+i)];
Or you could create your own number to string conversion function. There may be better ways, but here's an idea:
function s = convertnum(n)
if n > 9
s = [convertnum(floor(n/10)), char(48+mod(n,10))];
else
s = char(48+n);
end
end
Then use it like this:
fId = ['L', convertnum(i)];
EDIT
An alternative conversion function based on comments:
function s = convertnum(n)
s = [];
while n > 0
d = mod(n,10);
s = [char(48+d), s];
n = (n-d)/10;
end
end
Upvotes: 4