MATLAB Answers

## geometric mean month by month

Asked by Saad

### Saad (view profile)

on 23 May 2013

Dear All,

```I need some help please.
I have two columns in a matrix B.
B=[A, X];
X is a column vector that contains different daily observations.
A is a column vector that contains the number of the month (for example for January it has "1" for february "2" etc till December where it has "12").
```
```Column X has daily data for January, Feb till december. Thus Column A has numbers that change according to the month number. For instance, for january, Column A will have thirty one "1" corresponding to 31 days in january and twenty nine "2" corresponding to 29 days in February until the end of the year then i will start again with january with "1" and february with "2" etc till december .
```

What I would like to do is to do the gemetric mean of the values of X for similar values of A. Basically, it is like if Iam doing a geometric mean month by month untill the end of my data series. How can I do that please? I am stuck in this. ANy help is much appreciated. Best

S

## 3 Answers

Answer by Saad

### Saad (view profile)

on 23 May 2013

Or maybe simpler I could just pick the first and the last day of the month and do a geometric mean of all values in between. Any ideas on how I can do that? Thank you very much

### Eli Duenisch (view profile)

Answer by Eli Duenisch

### Eli Duenisch (view profile)

on 23 May 2013
Edited by Azzi Abdelmalek

### Azzi Abdelmalek (view profile)

on 23 May 2013

Use logical indexing to obtain indices belonging to the same month and calculate the geometric mean for each month:

```if true
for i=1:12, res(i)=geomean(X(A==i)); end
end
```

If you have no statistics toolbox installed you also need to write a function geomean() that calculates the geometric mean.

Saad

### Saad (view profile)

on 23 May 2013

Hi Eli Thank you for your answer. I am not looking to geomean all january values or all february values but each year seperately. Thank you

Andrei Bobrov

### Andrei Bobrov (view profile)

on 25 May 2013

See ADD part in my answer.

### Andrei Bobrov (view profile)

Answer by Andrei Bobrov

### Andrei Bobrov (view profile)

on 23 May 2013
Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

on 25 May 2013
```out = accumarray(B(:,2),B(:,1),[],@geomean);
```

ADD

if the second column of your data is the same as:

```b = arrayfun(@(x)x*ones(randi(7),1),repmat((1:12)',3,1),'un',0);
b = cat(1,b{:});
```

and all your array (B):

```B = [randi(7,numel(b),1), b];
```

solution:

```out = accumarray(B(:,2:3),B(:,1),[],@geomean);
```

#### 0 Comments

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

New to MATLAB?