Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
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

Respuesta aceptada

the cyclist
the cyclist el 21 de Oct. de 2022
Editada: the cyclist el 21 de Oct. de 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?

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by