user1077071
user1077071

Reputation: 961

How to calculate the centroid of a matrix?

I have the following 5x5 Matrix A:

1 0 0 0 0 
1 1 1 0 0 
1 0 1 0 1 
0 0 1 1 1 
0 0 0 0 1

I am trying to find the centroid in MATLAB so I can find the scatter matrix with:

Scatter = A*Centroid*A'

Upvotes: 3

Views: 29105

Answers (2)

Vidar
Vidar

Reputation: 4221

If you by centroid mean the "center of mass" for the matrix, you need to account for the placement each '1' has in your matrix. I have done this below by using the meshgrid function:

M =[    1 0 0 0 0; 
        1 1 1 0 0; 
        1 0 1 0 1; 
        0 0 1 1 1; 
        0 0 0 0 1];

[rows cols] = size(M);

y = 1:rows;
x = 1:cols;

[X Y] = meshgrid(x,y);

cY = mean(Y(M==1))
cX = mean(X(M==1))

Produces cX=3 and cY=3;

For

M = [1 0 0;
     0 0 0;
     0 0 1];

the result is cX=2;cY=2, as expected.

Upvotes: 5

Mansoor Siddiqui
Mansoor Siddiqui

Reputation: 21663

The centroid is simply the mean average computed separately for each dimension.

To find the centroid of each of the rows of your matrix A, you can call the mean function:

centroid = mean(A);

The above call to mean operates on rows by default. If you want to get the centroid of the columns of A, then you need to call mean as follows:

centroid = mean(A, 2);

Upvotes: 2

Related Questions