在matlab中将不同的字符转换为数字

convert different chars to number in matlab

Please help me with the following problem:

In matlab, I have an Nx3 char variable, where N can vary depending on the input. Let's say N = 5 and I have the following variable A (5x3 char):

A = [' 1M';
     ' 5D';
     '10Y';
     '15W';
     '20Y']

A 始终为 Nx3,并且只能占用 'D'、'W'、'M'、'Y',因此没有微秒。
有没有办法定义一个新变量 B,其值是变量 A 中的数字,以年表示,即 B=[1/12; 5/365; 10; 15/52; 20]?

到目前为止我尝试过但没有奏效的方法(M 的示例):

outc = mat2cell(A, ones(size(A,1),1), size(A,2));
for k = 1:length(outc) 
    if  outc{k} = '\w*M' 
        outc{k} = strrep(outc, 'M', '');
        outc2(k) = cellfun(@str2num, outc);
        outc2(k) = outc2(k)./12;
    end
end

Thank you for your help!

您可以设置一个将字符映射到数字的查找 table。在你的例子中,你有一个查找 table 映射 'D' 到 365,'W' 到 52,'M' 到 12 和 'Y' 到 1。您可以使用 containers.Map 轻松做到这一点。具体来说,您需要这样设置:

map = containers.Map({'D', 'W', 'M', 'Y'}, {365, 52, 12, 1});

这将每个字符映射到我们谈到的每个数字。接下来,, you'd convert each row of your character matrix to a cell array. However, I would also trim out any whitespace via strtrim让我们的分析更简单:

B = mat2cell(A, ones(size(A,1),1));
B = strtrim(B); %// Trim out whitespace

现在,您所要做的就是遍历每个单元格,将最后一个之前的所有字符转换为数字,然后使用最后一个字符并引用我们的查找table吐出正确的数字:

out = cellfun(@(x) str2num(x(1:end-1)) / map(x(end)), B);

我们得到:

out =

    0.0833
    0.0137
   10.0000
    0.2885
   20.0000

在转换为浮点数之前将其与小数形式的实际数字进行比较:

>> out2 = [1/12, 5/365, 10, 15/52, 20]

out2 =

    0.0833    0.0137   10.0000    0.2885   20.0000

我觉得不错!


用于复制和粘贴:

A = [' 1M';
     ' 5D';
     '10Y';
     '15W';
     '20Y'];
map = containers.Map({'D', 'W', 'M', 'Y'}, {365, 52, 12, 1});
B = mat2cell(A, ones(size(A,1),1));
B = strtrim(B); %// Trim out whitespace
out = cellfun(@(x) str2num(x(1:end-1)) / map(x(end)), B);

这是一种类似于 , but using a regular expression (regexprep) 而不是地图的方法:

B = mat2cell(A, ones(size(A,1),1)); %// convert each line to a cell
B = regexprep(B, {'Y' 'M' 'W' 'D' }, {'' '/12' '/52' '/365'}); %// replace letters
B = cellfun(@str2num, B); %// convert from strings to numbers

对于

A = [' 1M';
     ' 5D';
     '10Y';
     '15W';
     '20Y'];

这给出了

B =
    0.0833
    0.0137
   10.0000
    0.2885
   20.0000