MATLAB:字母数字字符串提取

时间:2014-11-22 14:06:31

标签: matlab char type-conversion

作为前言,我一直在寻找解决方案,我尝试了无数的代码,但没有一个适用于特定情况。

我有一个变量,它是不同英国公司的注册号。数据最初来自Stata,我不得不使用代码将非数字数据导入Matlab。该变量(regno)在观察18000(大约)之前是数字。从那时起它变成了带字母和数字的注册号。

我写了一个非常粗略的循环,抓住了初始变量(单元格),取出双引号,然后将字符提取到另一个矩阵(双精度)。代码是:

regno2 = strrep(regno,'"','');
regno3 = cell2mat(regno2);
regno4 = [];
    for i = 1:size(regno3,1);
    regno4(i,1) = str2double(regno3(i,1:8));
    end

对于包含字母和数字的变量,我得到NaN。我需要将变量作为double,以便在MatLab中将它们用作虚拟指示符变量。有什么想法吗?

由于

1 个答案:

答案 0 :(得分:1)

好的,我不确定你是否一直需要信件,但regular expressions 可能会执行你想要的信件。

这是一个帮助您入门的简单示例;在这种情况下,我使用正则表达式来查找条目中的数字。

clear

%// Create dummy entries
Case1 = 'NI000166';
Case2 = '12ABC345';

%// Put them in a cell array, like what you have.
CasesCell = {Case1;Case2};

%// Use regexp to locate the numbers in the expression. This will give the indices of the numbers, i.e. their position within each entry. Note that regexp can operate on cell arrays, which is useful to us here.
NumberIndices = regexp(CasesCell,'\d');

%// Here we use cellfun to fetch the actual values in each entry, based on the indices calculated above.
NumbersCell = cellfun(@(x,y) x(y),CasesCell,NumberIndices,'uni',0)

现在NumbersCell看起来像这样:

NumbersCell = 

    '000166'
    '12345'

您可以使用str2num(或srt2double)将其转换为数字,然后就可以了。

请注意,在您拥有00001234或SC001234的情况下,regexp给出的值将被视为不同,因此不会导致问题。如果变量具有不同的长度,然后您有相似的数字,那么您需要添加一些带有regexp的代码来考虑这些字母。 希望有所帮助!如果你需要澄清或者我误解了什么,请告诉我!