Finding the averages for a unique value.
Ältere Kommentare anzeigen

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.
Antworten (3)
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, [])'
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 Kommentare
Mohana
am 24 Nov. 2015
Stephen23
am 24 Nov. 2015
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.
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?
Andrei Bobrov
am 24 Nov. 2015
Bearbeitet: Andrei Bobrov
am 24 Nov. 2015
a - your array
[ii,jj] = ndgrid(a(:,1),1:5);
out = [unique(a(:,1)), accumarray([ii(:),jj(:)],reshape(a(:,2:end),[],1),[],@mean)];
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!