Filter löschen
Filter löschen

How to get a for to end just before Index exceeds the number of array elements?

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

the cyclist
the cyclist am 21 Okt. 2022
Bearbeitet: the cyclist am 21 Okt. 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?

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by