Remove cell that contains strings of another cell array

33 ビュー (過去 30 日間)
chlor thanks
chlor thanks 2016 年 8 月 8 日
回答済み: Sean Mahnken 2019 年 3 月 28 日
Input:
a={'Time12:30','Time12:40','Time1:40', 'Time2:40'};
b={'12:', '1:'};
Wanted Output: (delete from "a" all cells containing string listed in "b")
a={'Time2:40'}
I have tried:
for k = 1 : length(a)
for kk = 1 : length(b)
if any(~ismember(b{kk}, a{k}))
a(k) = [];
break;
end
end
end
However this gives me error of such:
Index exceeds matrix dimensions.
I am confused by the error and any guidance is appreciated! Thank you for reading my post.

採用された回答

James Tursa
James Tursa 2016 年 8 月 8 日
編集済み: James Tursa 2016 年 8 月 8 日
You are changing the size of a in the loop with this line:
a(k) = [];
So subsequent iteration indexes that depend on the length of a will fail. Maybe save the indexes to delete in the loop, and then delete them all at once at the end. E.g., something like this:
a={'Time12:30','Time12:40','Time1:40', 'Time2:40'};
b={'12:', '1:'};
x = false(size(a)); % <-- Indexes to delete, start out nobody deleted
for k=1:numel(b)
x = x | ~cellfun(@isempty,strfind(a,b{k})); % <-- Flag the ones that b{k} matches
end
a(x) = []; % <-- Delete all the flagged lines at once
  1 件のコメント
chlor thanks
chlor thanks 2016 年 8 月 8 日
Thank you for your help James!

サインインしてコメントする。

その他の回答 (2 件)

Stalin Samuel
Stalin Samuel 2016 年 8 月 8 日
strfind(a, b(kk))%find a string from string array

Sean Mahnken
Sean Mahnken 2019 年 3 月 28 日
You should be able to just do the k loop backwards:
for k = length(a):-1:1
for kk = 1 : length(b)
if any(~ismember(b{kk}, a{k}))
a(k) = [];
break;
end
end
end

カテゴリ

Help Center および File ExchangeCalendar についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by