# Remove all the entries = 0 from a TVectorD

Hello,

I have a TVectorD with many entries equal to 0 and I’d like to create a new TVectorD which contains all the entries non equal to 0. Since my TVectorD contains a lot of entries (more than 1 million), I’d like to avoid to loop on it. Is there a way to do it ?
thanks !

Marie

Hi Marie,

You will have to loop across the vector elements somewhere .
Try something like:

``````Int_t n1 = 1000;
TVectorD v1(n1);

Double_t *pV1 = v1.GetMatrixArray();
TVectorD v2(v1);
Double_t *pV2 = v2.GetMatrixArray();
Int n2 = 0;
for (Int_t i = 0; i < n1; i++)
{
if (pV1[i] != 0.)
pV2[n++] = pV1[i];
}
if (n1 != n2)
v2.ResizeTo(n2);``````

Eddy

Is there any reason to make a copy?

``````Int_t n1 = 1000;
TVectorD v1(n1);
// fill v1 magically

Double_t *pV1 = v1.GetMatrixArray();
Int n2 = 0;
for (Int_t i = 0; i < n1; ++i)
{
if (pV1[i] != 0.)
{
if (n != i)
{
pV1[n2++] = pV1[i];
} // if n different from i
++n;
} // if non-zero value
} // for i
if (n1 != n2)
{
v1.ResizeTo(n2);
}``````

Yup, the user asked for a new vector

Note to self: Try reading before responding.

Note to Marie: If you have a really large vector and you don’t need the original, you may be better off with shrinking the one in place.

Cheers,
Charles

Hello,

thanks for your answers. Actually, I convinced myself that I have to do a loop anyway, and I want to keep the original vector also ! I did a loop on the vector entries : is it more efficient to create first an array containing all the entries of the vector (using GetMatrixArray function, as suggested by Eddy) and then to loop on that array ?

Marie

Hi Marie,

I am not sure I understand your question .

``TVectorD v2(v1);``
``TVectorD v2(v1.GetNrows());``