如何让索引功能更快?

时间:2015-07-16 02:48:26

标签: arrays matlab indexing struct cell

所以给定一个struct数组,Index with fields,Word,Documents,Locations,它需要一个char数组的单元格数组并将其索引到Index中,并且还记录索引出现的文档的DocNums。

function Index = InsertDoc(Index, newDoc, DocNum)
    for i = 1:numel(newDoc) 
        contains = any(strcmpi(newDoc(i),[Index.Word]));
        if any(contains);
            curr = find(strcmpi(newDoc(i),[Index.Word]),true);
            Index(curr).Documents{1} = unique([Index(curr).Documents{1},DocNum]);
            if (numel(Index(curr).Documents{1}) ~= numel(Index(curr).Locations))
                Index(curr).Locations{end+1} = [i];
            else
                Index(curr).Locations{end} = [Index(curr).Locations{end},i];
            end

        else 
            curr = numel(Index) + 1;
            Index(curr).Word = [newDoc(i)];
            Index(curr).Documents = {DocNum};
            Index(curr).Locations = {[i]};
        end
    end
end

例如

Doc1 = {'Matlab', 'is', 'awesome'};
Doc2 = {'Programming', 'is', 'very', 'very', 'fun'};
Doc3 = {'I', 'love', 'Matlab','very','much};

someIndex = InitializeIndex;
% InitializeIndex just creates struct array with the given fields and empty cell arrays
someIndex = InsertDoc(someIndex, Doc1, 1);
someIndex = InsertDoc(someIndex, Doc2, 2);
someIndex = InsertDoc(someIndex, Doc3, 3);

结果将是 someIndex(1)

Word: 'Matlab'
Documents: [1 3]
Locations: {[1] [3]}

someIndex(2)

Word: 'is'
Documents: [1 2]
Locations: {[2] [2]}

someIndex(5)

Word: 'very'
Documents: [2 3]
Locations: {[3 4] [4]}

我需要能够使用带有各种单词的20000个元素的结构数组来运行它,现在需要花费大量时间来完成索引。如何改进此算法?

1 个答案:

答案 0 :(得分:1)

在循环开始之前,尝试allocate memory为您的单元格数组“索引”。