Mask with a for loop

2 visualizaciones (últimos 30 días)
Alexya
Alexya el 7 de Mzo. de 2023
Editada: Matt J el 7 de Mzo. de 2023
I wrote this code that is finding the data i want to remove, i dont know how to mask to remove it from the original vector
vec = [2 3 0 0 7 8 0]
the answer is supposed to be [2 0 0 7 0]
but im getting [3 8], the opposite of what I want, how do i mask to flip this
function [newVec] = removeData(vec)
newVec = [];
for x = 1:length(vec) %don't have to go backwards because we aren't deleting
if vec(x) ~= 0 && vec(x + 1) == 0%checking for not evens
newVec = [newVec vec(x)];
end
end
end

Respuestas (3)

David Hill
David Hill el 7 de Mzo. de 2023
removeData([2 3 0 0 7 8 0])
ans = 1×5
2 0 0 7 0
function [newVec] = removeData(vec)
newVec = zeros(size(vec));
for x = 1:length(vec) %don't have to go backwards because we aren't deleting
if vec(x) ~= 0 && vec(x + 1) == 0%checking for not evens
newVec(x)=1;
end
end
newVec=vec(~newVec);
end

Matt J
Matt J el 7 de Mzo. de 2023
Editada: Matt J el 7 de Mzo. de 2023
removeData([2 3 0 0 7 8 0])
ans = 1×5
2 0 0 7 0
function newVec = removeData(vec)
newVec = vec;
newVec( vec(1:end-1) & ~vec(2:end) ) = [];
end

Voss
Voss el 7 de Mzo. de 2023
removeData([2 3 0 0 7 8 0])
ans = 1×5
2 0 0 7 0
function vec = removeData(vec)
x = 1;
while x < numel(vec)
if vec(x) ~= 0 && vec(x + 1) == 0%checking for not evens
vec(x) = [];
else
x = x + 1;
end
end
end

Categorías

Más información sobre Manage Products en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by