How to calculate the centroid of a matrix?
26,591
Solution 1
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.
Solution 2
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);
Author by
user1077071
Updated on July 09, 2022Comments
-
user1077071 almost 2 years
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'