使用m.file的Word搜索算法



我已经在Matlab上使用多个字符串的单元格实现了我的算法,但我似乎无法通过读取文件来实现。

在Matlab中,我为每一行创建字符串单元格,我们称它们为line。

得到

     line= 'string1' 'string2' etc
     line= 'string 5' 'string7'...
     line=...

等等。我有一百多行要读。

我要做的是比较从第一行到它自己的单词。然后将第一行和第二行合并,并将第二行的单词与合并后的单元格进行比较。我将读取的每个单元格累加起来,并与最后读取的单元格进行比较。

下面是我在

上的代码

每一行= a,b,c,d,…

for(i=1:length(a))
for(j=1:length(a))
  AA=ismember(a,a)
  end
  combine=[a,b]
  [unC,i]=unique(combine, 'first')
  sorted=combine(sort(i))
  for(i=1:length(sorted))
for(j=1:length(b))
  AB=ismember(sorted,b)
 end
 end
 combine1=[a,b,c]

…当我读取我的文件,我创建了一个while循环读取整个脚本,直到结束,所以我怎么能实现我的算法,如果我所有的单元格的字符串有相同的名字?

    while~feof(fid)
    out=fgetl(fid)
    if isempty(out)||strncmp(out, '%', 1)||~ischar(out)
    continue
    end
    line=regexp(line, ' ', 'split')

假设您的数据文件名为data.txt,其内容为:

string1 string2 string3 string4
string2 string3 
string4 string5 string6

只保留第一个唯一出现的一个非常简单的方法是:

% Parse everything in one go
fid = fopen('C:Usersok1011Desktopdata.txt');
out = textscan(fid,'%s');
fclose(fid);
unique(out{1})
ans = 
    'string1'
    'string2'
    'string3'
    'string4'
    'string5'
    'string6'

如前所述,如果:

此方法可能不起作用:
  • 你的数据文件有不规则
  • 你需要比较索引

编辑:性能解决方案

% Parse in bulk and split (assuming you don't know maximum 
%number of strings in a line, otherwise you can use textscan alone)
fid = fopen('C:Usersok1011Desktopdata.txt');
out = textscan(fid,'%s','Delimiter','n');
out = regexp(out{1},' ','split');
fclose(fid);
% Preallocate unique comb
comb = unique([out{:}]); % you might need to remove empty strings from here
% preallocate idx
m   = size(out,1);
idx = false(m,size(comb,2));
% Loop for number of lines (rows)
for ii = 1:m
    idx(ii,:) = ismember(comb,out{ii});
end

注意,结果idx是:

idx =
     1     1     1     1     0     0
     0     1     1     0     0     0
     0     0     0     1     1     1

以这种形式保存它的优点是可以节省相对于单元格数组的空间(每个单元格会增加112字节的开销)。您还可以将其存储为稀疏数组,以潜在地提高存储成本。

另一件要注意的事情是,即使逻辑数组比正在索引的双数组长,只要超出的元素为假,你仍然可以使用它(通过上面问题的构造,idx满足了这个要求)。一个明确的例子:
A = 1:3;
A([true false true false false])

最新更新