Getting the mean value of a row in an array?
11 次查看(过去 30 天)
显示 更早的评论
I have the code
filename='Laramie2005_2015.dat'; %Wind data file
iminsamp=53;
yearno = 2006:2009;
for mo = 1:5
for yearidx = 1 : length(yearno)
yr = yearno(yearidx);
[dttm{mo,yearidx}, timemin{mo,yearidx}, wnddatenum{mo,yearidx}, wndspeed{mo,yearidx}, wnddir{mo,yearidx}, pres{mo,yearidx}, temp{mo,yearidx}] = RdNCDCData(filename, mo, yr, iminsamp);
end
end
which gives my desired variables as an array that is [mo,yearidx] in size with each one of the values varying in size as a 1:n row maxtix. I am looking to get the average for each row but am only getting the average of each column for each row using ave(x)=arrayfun(@(x) mean(wndspeed{x}),x) which in turn produces a matrix. Is there a way to get a single average for each month using something like that?
1 个评论
Kirby Fears
2015-9-17
Chris,
I'm having trouble understanding your question. Do want to take the average (collapsing dimension 2) of an N x M cell where each cell contains a 1 x L numeric array (where L varies for each cell)? Is the desired output a N x 1 vector of averages?
回答(2 个)
Jon
2015-9-17
编辑:Jon
2015-9-18
If you have an array called myarray that is mo x yearidx (as you state in your question) and you want the average of all mo == j, then you could just write
meanmo(j) = mean(myarray(myarray(:,1)==j),:);
where j is the index of the month you want to average over. Just replace "myarray" with whichever variable you want to average over.
Edit: Kirby pointed out that you're using cell storage instead of matrix, so to use my method you'd need to convert your cell to a matrix first:
myarray = cell2mat(temp);
1 个评论
Kirby Fears
2015-9-17
Jon,
In Chris' example, he appears to have a "mo x yearidx" cell, not an array. He's using curly brackets inside of his for loop.
Kirby Fears
2015-9-17
编辑:Kirby Fears
2015-9-17
Chris,
I think you're looking for one of two things, but I'm not sure which. Try these out and see if it's the output you're looking for. If not, please try to clarify your question.
** Creating example data
sample{1,1}=ones(1,5);
sample{1,2}=2*ones(1,6);
sample{2,1}=3*ones(1,4);
sample{2,2}=4*ones(1,5);
1. First interpretation of question: one mean per cell.
means=cellfun(@(c)mean(c),sample);
2. Second interpretation of question: one mean per "mo".
sums=cellfun(@(c)sum(c),sample);
counts=cellfun(@(c)numel(c),sample);
means=sum(sums,2)./sum(counts,2);
Hope this helps.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!