MATLAB代码错误

MATLAB代码错误,matlab,list,elements,Matlab,List,Elements,下面是我的MATLAB函数,它包含一些错误,所以希望任何专家都能纠正或指出错误和改进的方法。我使用MatlabR2015A function L = remove_all(L,E) % remove_all(List,element) - delete all occurrences of E from L for Index = length(L.elements):-1:1 if isequal(E,L.elements{Index}) L.elements(Inde

下面是我的MATLAB函数,它包含一些错误,所以希望任何专家都能纠正或指出错误和改进的方法。我使用MatlabR2015A

function L = remove_all(L,E)
% remove_all(List,element) - delete all occurrences of E from L
for Index = length(L.elements):-1:1
    if isequal(E,L.elements{Index})
        L.elements(Index) = [];
    end 
end

通过删除该结构中的元素,但忘记在删除元素时结构的长度会发生变化,从而在
for
循环中对结构进行变异。因此,每次删除时结构的长度都会减少,并且在删除项目时最终会超出范围。具体地说,您使用
length
捕获列表的初始长度,但是当您删除项目时,该长度不再相同,并且
for
循环不知道这一事实。因此,由于错误地删除项,最终会出现越界错误

解决此问题的一种方法是保存要从结构中删除的所有位置,并且在完成
for
循环后,立即删除所有位置:

function L = remove_all(L,E)
% remove_all(List,element) - delete all occurrences of E from L
indices = []; %// New - keep the locations that need to be removed
for Index = length(L.elements):-1:1
    if isequal(E,L.elements{Index})
        indices = [indices; Index]; %// Add to list if equal
    end 
end
L.elements(indices) = []; %// Remove all entries at once

虽然rayryeng的回答指出了错误并纠正了错误,但我仍然想尝试使用
cellfun
的单行代码版本:

function L = remove_all(L,E)
% remove_all(List,element) - delete all occurrences of E from L
L.elements(cellfun(@(x) x == E, L.elements)) = [];
end

我们不是读心术的人。MATLAB给你的错误到底是什么?还请提供预期的输入和输出。首先,我不知道
L
包含什么,也不知道字段
元素应该包含什么。同意,如果您编辑它来解释您期望看到的内容和实际看到的内容,问题会更好。您得到了什么错误。。。?请在帖子中提及。我们中有人帮过你吗?想知道这在性能上与
for
循环相比如何
cellfun
本质上是引擎盖下的一个环。。。但是非常好:)