How to get a for to end just before Index exceeds the number of array elements?
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
the cyclist
on 21 Oct 2022
Edited: the cyclist
on 21 Oct 2022
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?
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!