Finding the averages for a unique value.

I have a data set as shown, I need to find the average values of 1 in column A w.r.t to column B, C, etc.
For example average of 1 = average of 0.7, 0.9, 1.1, 1.3, similarly
2 = average of 1.5, 1.7, 1.9
similarly for 3 , 4, ..... and on and similarly for the columns C, D, E, F.
I have written a code as detailed below but I am getting index exceeds matrix error.
clc
clear all
load input.txt
d=input(:,1);
Tm=input(:,2);
Atmp=input(:,3);
Mxtmp=input(:,4);
Mntmp=input(:,5);
Rh=input(:,6);
[u i j] = unique(d);
D = length(d) % No. of data vectors
U = length(u) % No. of unique dates
I = length(i)
J = length(j)
M = zeros(I,5); % Initialize daily means
for k=1:J
n=find(u==d(k));
M(j,:)= mean(input(u(d),2:6))
end
Can any one help.
Thanks in advance.

回答(3 个)

Thorsten
Thorsten 2015-11-24
编辑:Thorsten 2015-11-24
X = input;
A = X(:,1);
MC = arrayfun(@(i) mean(X(A == i, 2:end)), unique(A), 'UniformOutput', false);
M = reshape(cell2mat(MC), size(X,2)-1, [])'
This is exactly what the function accumarray is designed for! Use it either in a loop:
X = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5;...
0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2.1, 2.3, 2.5, 2.7, 2.9, 3.1, 3.3, 3.5;...
0.78,0.16,0.86,0.68,0.72,0.76,0.80,0.84,0.88,0.92,0.96,1.00,1.04,1.08,0.12].'
%
for k = size(X,2):-1:1
out(:,k) = accumarray(X(:,1),X(:,k),[],@mean);
end
Or all on one line using cellfun:
mat = cell2mat(cellfun(@(V)accumarray(X(:,1),V,[],@mean),num2cell(X,1),'UniformOutput',false))
Both create the same numeric output:
mat =
1 1.00000 0.62000
2 1.70000 0.76000
3 2.30000 0.88000
4 2.80000 0.98000
5 3.30000 0.74667

4 个评论

I want to load the input file from graphic interface which is working fine and then find the result, since there are several files that need to be processed. This is only a sample data file.
So try it! As long as your data file has the same format as your example data (first column natural number group index), then this method will work.
Mohana
Mohana 2015-11-24
编辑:Mohana 2015-11-24
I am getting the following error for the line
out = cell2mat(cellfun(@(V)accumarray(X(:,1),V,[],@mean),num2cell(X(:,2:end),1),'UniformOutput',false
Expression or statement is incorrect--possibly unbalanced (, {, or [.
It is not clear whether the line is a single line command or a combination of multiple line.
You did not copy the final two closing parentheses '))' at the end of the functions. I just copied the complete line and it worked without error.
I wrote in my answer "...on one line...", so how is this not clear that this code should be on one single line?

请先登录,再进行评论。

a - your array
[ii,jj] = ndgrid(a(:,1),1:5);
out = [unique(a(:,1)), accumarray([ii(:),jj(:)],reshape(a(:,2:end),[],1),[],@mean)];

类别

在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息

产品

标签

提问:

2015-11-24

编辑:

2015-11-24

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by