可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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
回答2:
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
回答3:
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 #include using namespace std; string num2str(int number) { string s; s = to_string(number); return s; }