how to delete specific entries (based on a condition) in an array?

37 ビュー (過去 30 日間)
Subrat kumar sahoo
Subrat kumar sahoo 2012 年 6 月 28 日
Hi I wrote a small code, which goes as follows: %start of code
a = [0 12 16 13 14 25 12 1 170 172 32 5 171]; for i = 1:length(a); if a(i) < 18 a(i) = []; end end % end of code
The intent is to eliminate those entries which have values less than 18. It gives me two errors. Error One- it doesnt execute the entire length of a, stops in between with an error message that --- ??? Attempted to access a(9); index out of bounds because numel(a)=8.
Error in ==> array_elimination at 7 if a(i) < 18 Error two- It doesnt eliminate all the entries <18, it just eliminates the alternate entries. Thats strange and makes me feel that its a bug in matlab!! Need help

採用された回答

Honglei Chen
Honglei Chen 2012 年 6 月 28 日
編集済み: Honglei Chen 2012 年 6 月 28 日
You are changing a every time when you found an element less than 18, so when the iteration gets to the original array length, it is out of bound. You can achieve what you want by the following command
a(a<18) = []
  1 件のコメント
Subrat kumar sahoo
Subrat kumar sahoo 2012 年 6 月 28 日
Perfect, Thanks Honglei, Didnt occur to me :( wasted half a day Thanks again

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by