How to get a for to end just before Index exceeds the number of array elements?
2 ビュー (過去 30 日間)
古いコメントを表示
I need to write a code that takes a vector and deletes every value in the vector that is directly followed by a 0 unless the value itself is a zero ( then it should be remain). I got it to work until i equals the length of vec and then it says the 'Index exceeds the number of array elements.' I know what the issue is but I do not know how to code around it. I have also provided some test codes.
% Test Codes
vec = [2 3 0 0 7 8 0]
% ans = [2 0 0 7 0]
% vec = [10 0 8 2 5 0]
% ans = [0 8 2 0]
% vec = [0 0 0 0 2 3 5 0 8]
% ans = [0 0 0 0 2 3 0 8]
ans = [];
for i = 1:length(vec)
if vec(i+1) == 0 & vec(i) ~= 0
ans = [ans]
elseif vec(i) == 0 && vec(i+1) == 0
ans = [ans vec(i)]
else
ans = [ans vec(i)]
end
i = i + 1
end
0 件のコメント
採用された回答
the cyclist
2022 年 10 月 21 日
編集済み: the cyclist
2022 年 10 月 21 日
This seems like homework, so I will give you a hint instead of just answering.
It seems like according to the rules, the last element is never removed. Can you think of a way to modify your code, such that it does not check the last element, and/or just automatically keeps it?
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!