簡體   English   中英

MATLAB代碼錯誤

[英]MATLAB Code error

以下是我的MATLAB函數,其中包含一些錯誤,希望任何專家都能糾正或指出錯誤以及改進方法。 我使用MATLAB R2015a

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的1行代碼版本:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM