在matlab中对数组进行比较和删除

时间:2013-01-04 14:53:27

标签: arrays matlab

我正在尝试编写一个简短的代码来将.m文件(testin1.m)读入一个数组,并搜索一个特定的单词('auto')。如果找到匹配,请将其删除。我有以下代码,请帮我弄清楚我的错误。

fid = fopen('testin1.m');
 txt = textscan(fid,'%s');
fclose(fid);
m_file_idx = 1;
data=['auto'];
B=cellstr(data);
 for idx = i : length(txt)
 A=txt{i};
 is_auto=isequal(A, B);
 if is_auto==0
 txt{i}=[];
 end
end

如果txt {i} = auto,那么它应该删除该行。

3 个答案:

答案 0 :(得分:2)

这是一个错误,我已多次击中很多次:

设置txt(i) = []时,更改数组的长度。您的for循环条件不再有效。

更好的选择是使用强大的索引功能:

A(find(condition)) = [];

或考虑到长度的变化:

A(i) = [];
i--; % <-- or i++, it is too early to think, but you get the idea
编辑:我刚刚注意到您在程序中也使用了A。我只是一些随机变量名,与你可能使用的A不一样

答案 1 :(得分:2)

AK4749的答案在显示你出错的地方是绝对正确的。我将为您添加一个替代解决方案,这个解决方案更短:

C = textread('testin1.m', '%s', 'delimiter', '\n');
C = C(cellfun(@isempty, regexp(C, 'auto')));

就是这样!

编辑#1:修改了答案以删除包含单词'auto'的行,而不只是单词本身 编辑#2:修改答案以接受正则表达式。

答案 2 :(得分:1)

设置txt(i) = []时,您更改了数组的长度,但循环索引不考虑更改。您可以使用logical indexing来避免循环和问题。

示例:

wordToDelete = 'auto';
txt = {'foo', 'bar', 'auto', 'auto', 'baz', 'auto'}
match = strcmp(wordToDelete, txt)
txt = txt(~match)

输出:

txt = 
    'foo'    'bar'    'auto'    'auto'    'baz'    'auto'
match =
     0     0     1     1     0     1
txt = 
    'foo'    'bar'    'baz'