Hi all,I have a problem with the following sample code:
M=[1 2 3 4 5 6 7 8 9 10] for i=1:length(M) M(i)=[] end
My code is not complete, but my problem is that when one row is omitted from the matrix, the size reduces to 9, so the code gets stock with an error to find M(10). Actually, I want to update the cell size in for loop. In my code, I must make some rows empty, I can not keep them. Thanks

 採用された回答

Voss
Voss 2024 年 4 月 23 日

0 投票

You can iterate backwards, so that subsequent indexing is never off the end of M.
Example:
M=[1 2 3 4 5 6 7 8 9 10];
for i=length(M):-1:1
M(i)=[];
end
M
M = 1x0 empty double row vector
Or you can store the indices to delete, and delete them all after the loop.
Example, using numeric indices:
M=[1 2 3 4 5 6 7 8 9 10];
to_delete = [];
for i=1:length(M)
to_delete(end+1) = i;
end
M(to_delete)=[];
M
M = 1x0 empty double row vector
Example, using logical indices:
M=[1 2 3 4 5 6 7 8 9 10];
to_delete = false(1,numel(M));
for i=1:length(M)
to_delete(i) = true;
end
M(to_delete)=[];
M
M = 1x0 empty double row vector

4 件のコメント

Neda
Neda 2024 年 4 月 23 日
Thank you so much for your answer !!!
Voss
Voss 2024 年 4 月 23 日
You're welcome!
Neda
Neda 2024 年 4 月 24 日
Dear Voss;
Is there any way that I can send you my full code to check, since I still have problem in my code? my code has a main function and some functions !!!
Thanks
Voss
Voss 2024 年 4 月 24 日
Neda,
Yes, please post a new question, upload your code file(s) there using the paperclip button, and specify what problems you are having.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeApp Building についてさらに検索

タグ

質問済み:

2024 年 4 月 23 日

コメント済み:

2024 年 4 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by