簡體   English   中英

不支持Matlab編碼器num2str

[英]Matlab coder num2str not supported

我正在嘗試通過使用Matlab編碼器將Matlab項目轉換為C ++。 我在代碼中很少使用num2str函數。 但是,當嘗試使用Matlab編碼器構建項目時,出現以下錯誤。

“獨立代碼生成不支持功能'num2str'。”

在需要為結構創建字段標識符的情況下,可以使用此功能。

例如:

for i=1:numel(bvec)
      fId = ['L', num2str(i)];
      tmp = mystruct.(fId);  
      % do some work here  
end

我可以使用函數num2str的替代方法來轉換項目嗎?

使用sprintf很容易,但是我不確定是否可以使用它?

fId = sprintf('L%d', i);

如果numel(bvec)的范圍是0到9,則可以使用char

fId = ['L', char(48+i)];

或者,您可以創建自己的數字到字符串的轉換功能。 可能有更好的方法,但這是一個主意:

function s = convertnum(n)
   if n > 9
      s = [convertnum(floor(n/10)), char(48+mod(n,10))];
   else
      s = char(48+n);
   end
end

然后像這樣使用它:

fId = ['L', convertnum(i)];

編輯

一種基於注釋的替代轉換函數:

function s = convertnum(n)
   s = [];
   while n > 0
      d = mod(n,10);
      s = [char(48+d), s];
      n = (n-d)/10;
   end
end

我為Matlab2016a Coder編寫了以下代碼來替換num2str ,它還支持雙精度:

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

可以使用C ++中的to_string編寫與Matlab的num2str等效的函數。 請查看我的函數版本:

#include"stdafx.h"
#include <sstream>
#include <string.h>

using namespace std;

string num2str(int number)
{
    string s;
    s = to_string(number);
    return s;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM