# [vtk-developers] Proposed CenterOfMass function for vtkPoints

John Platt jcplatt at dsl.pipex.com
Thu Apr 1 04:31:21 EDT 2010

David,

You may like to check that numberOfPoints is not zero before the divide.

John.

----- Original Message -----
From: "David Doria" <daviddoria+vtk at gmail.com>
To: "VTK Developers" <vtk-developers at vtk.org>
Sent: Wednesday, March 31, 2010 10:30 PM
Subject: [vtk-developers] Proposed CenterOfMass function for vtkPoints

> Can we add a CenterOfMass(double[3]) function to vtkPoints?
>
> void vtkPoints::CenterOfMass(double center[3])
> {
>  center[0] = 0.0;
>  center[1] = 0.0;
>  center[2] = 0.0;
>
>  for(vtkIdType i = 0; i < this->GetNumberOfPoints(); i++)
>    {
>    double point[3];
>    this->GetPoint(i, point);
>
>    center[0] += point[0];
>    center[1] += point[1];
>    center[2] += point[2];
>    }
>
>  double numberOfPoints = static_cast<double>(this->GetNumberOfPoints());
>  center[0] /= numberOfPoints;
>  center[1] /= numberOfPoints;
>  center[2] /= numberOfPoints;
> }
>
> It would be used like this:
>
>  vtkSmartPointer<vtkPoints> points =
>      vtkSmartPointer<vtkPoints>::New();
>  points->InsertNextPoint(0,0,0);
>  points->InsertNextPoint(1,0,0);
>  points->InsertNextPoint(0,1,0);
>  points->InsertNextPoint(1,1,0);
>
>  double center[3];
>  points->CenterOfMass(center);
>  cout << "Center: " << center[0] << " " << center[1] << " " <<
> center[2] << endl;
>
> or like this:
>
>  vtkSmartPointer<vtkPoints> points =
>      vtkSmartPointer<vtkPoints>::New();
>  points->InsertNextPoint(0,0,0);
>  points->InsertNextPoint(1,0,0);
>  points->InsertNextPoint(0,1,0);
>  points->InsertNextPoint(1,1,0);
>
>  vtkSmartPointer<vtkPolyData> pd =
>      vtkSmartPointer<vtkPolyData>::New();
>  pd->SetPoints(points);
>
>  double center[3];
>  pd->GetPoints()->CenterOfMass(center);
>  cout << "Center: " << center[0] << " " << center[1] << " " <<
> center[2] << endl;
>
> The modified files and a demo are attached if anyone wants to try them
> out.
>
> Thanks,
>
> David
>

--------------------------------------------------------------------------------

> _______________________________________________
>
> Visit other Kitware open-source projects at
> http://www.kitware.com/opensource/opensource.html
>