## Octave code example

May 19, 2014 Leave a comment

This is one of the simpler code tasks I worked on. I use ‘R’ but since this is Octave my first attempt wasn’t generic. The *for* loop assumes that there are 2 columns in the matrix shown below. There is a way to modify it to be more generic but this an example to show my Octave skills !!

I have a matrix with 2 columns and a vector which has repeating sets of the numbers 3,2 and 1. The task is to calculate the mean of all values in each column of the matrix rows that are grouped by the numbers 3, 2 and 1. So I decided to add the vector as the 3rd column of the matrix.

### Matrix

### Vector

Add the vector as the 3rd column.

centroids = zeros(K, n);%Declare matrix to store the result X(:,end + 1 ) = idx;

Find the unique values of the 3rd column. The decimals do not matter here.

uidx = unique(X(:,3),"columns");

### Vector with unique elements

I use *find* to get all the *row numbers*(j) of the values in the matrix where the 3rd column matches each of the unique values(uidx)

for i = 1:size(uidx,1) [j,k]=find(X(:,3) == uidx(i) ); s = X(j,1); t = X(j,2); centroids(i,:) = [mean(s);mean(t)] end