Eliminating element if a vector

Suppose I have a vector of 6 elements i.e. [4 5 6 5 4 8].I want to write a code that should run across the column and when it encounters the value of 6, all the values should be made equal to zero regardless whether they are greater then 6 or smaller than it. The output should be like this [4 5 6 0 0 0]. I want to use this technique in image processing to make the values of the pixels below or above a certain threshold equal to zero when the threshold is detected.This process is repeated over all the columns in an image.

 Respuesta aceptada

Stephen23
Stephen23 el 20 de En. de 2016
Editada: Stephen23 el 20 de En. de 2016
Here is a simple method that you can apply to the entire matrix, without any loops:
thr = 6;
mat = randi(9,5)
%
idx = 0<cumsum(mat==thr,1);
idx([2:end,1],:) = idx;
idx(1,:) = false;
%
mat(idx) = 0
which displays the original random matrix:
mat =
8 6 7 8 1
5 5 6 5 6
9 1 7 2 7
9 6 2 9 1
9 5 6 6 5
and the one with the values after the first thr values replaced with zeros:
mat =
8 6 7 8 1
5 0 6 5 6
9 0 0 2 0
9 0 0 9 0
9 0 0 6 0

1 comentario

Andrei Bobrov
Andrei Bobrov el 20 de En. de 2016
Editada: Andrei Bobrov el 20 de En. de 2016
+1
Another variant:
mat = mat.*(cumsum(cumsum(mat == 6))<2);

Iniciar sesión para comentar.

Más respuestas (1)

Andrei Bobrov
Andrei Bobrov el 20 de En. de 2016
a = [4 5 6 5 4 8];
ii = find(a == 6,1,'first')
out = a;
out(ii+1:end)=0

Preguntada:

el 20 de En. de 2016

Editada:

el 20 de En. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by