Error using for loop to delete empty cell array elements

3 ビュー (過去 30 日間)
Jaya
Jaya 2021 年 10 月 31 日
編集済み: Jaya 2021 年 11 月 15 日
I want to completely delete the null elements of routes_log cell array. I use the following code.
temp_routes_log=routes_log
for i=1:numel(temp_routes_log)
if (isempty(temp_routes_log{i})==1)
routes_log(i)=[]
end
end
%routes_log can be like {0×0 double} {1×3 double} and I want to
% completely remove the {0×0 double} and make routes_log as just {1×3 double}
But I get error in the case when (for e.g.) 5th entry is null in temp_routes_log but as I am deleting the routes_log elements, the routes_log is no more containing 5 elements and it throws an error at
routes_log(i)=[]
I also tried storing the indices i and then deleting those routes_log elements directly but I some other error was coming. Please guide on how can I achieve the deletion.

採用された回答

per isakson
per isakson 2021 年 10 月 31 日
編集済み: per isakson 2021 年 10 月 31 日
Replace
for i=1:numel(temp_routes_log)
by
for i = numel(temp_routes_log) : -1 : 1 % loop from last to first element
OR if routes_log is large and speed becomes an issue
to_be_deleted = false(1,numel(routes_log))
for i=1:numel(temp_routes_log)
if isempty(temp_routes_log{i})
to_be_deleted(i) = true;
end
end
routes_log(to_be_deleted) = [];
Caveat: not tested
  1 件のコメント
Jaya
Jaya 2021 年 10 月 31 日
編集済み: Jaya 2021 年 11 月 15 日
For now, routes_log is not so big. So, I used the first solution. Thanks.
Update: The second method works too! I later encountered large sized routes_log & revisited this solution to try the second way.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by