Replace an element of a vector by also redefining the vector
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Konstantinos Tsitsilonis
el 3 de Ag. de 2017
Respondida: Julie Kraus
el 3 de Ag. de 2017
Hi all,
I would like to replace some elements of a vector Vec that have indices idx with NaN, to create a new vector VecNaN. However, using the usual code below
Vec(idx) = NaN;
redefines the vector Vec with the NaN elements. Instead I want to find a new vector VecNaN such that it is the same as Vec, but with the NaN elements in the indices idx.
Thanks for your help in advance,
KMT.
0 comentarios
Respuesta aceptada
Harry Vancao
el 3 de Ag. de 2017
You could do the following:
vecNaN = vec; vecNaN(idx) = NaN;
1 comentario
Jan
el 3 de Ag. de 2017
Editada: Jan
el 3 de Ag. de 2017
+1. This is usually the most efficient solution. You could save the copy of the overwritten elements also, which is easier, when idx is a logical index vector:
x = rand(1, 1000);
idx = (x > 0.9);
y(idx) = NaN;
y(~idx) = x(~idx);
This creates the vector y twice if the last element is not NaN. Better:
if idx(end)
y(idx) = NaN;
y(~idx) = x(~idx);
else
y(~idx) = x(~idx);
y(idx) = NaN;
end
Well, in most cases it is not worth the effort and Harry's suggestion is nice and efficient, although it "wastes" some time with copying elements, which are overwritten directly.
Más respuestas (1)
Julie Kraus
el 3 de Ag. de 2017
If I am understanding you correctly you want 2 vectors out, your original and a new vector with NaN's in idx locations.
VecNaN=Vec;
VecNaN(idx)=NaN;
0 comentarios
Ver también
Categorías
Más información sobre Get Started with MATLAB en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!