unequal arrays and basic calculations

2 次查看(过去 30 天)
Tiina
Tiina 2011-12-25
I want to reshape vector num to an averages vector as
Day time num
20050103 34200000 10
20050103 34205000 14
20050103 34210000 8
20050103 34215000 11
20050103 34220000 15
20050103 34225000 13
20050103 34230000 7
Assume I want to average over time each 4 intervals
Then I should have something like: 10.75 and 11.67
10.75= (10+14+8+11)/4
11.67=(15+13+7)/3
If I do something like
av=mean(reshape(num, [4 length(num/4]))';
I obviously get an issue with the size of the vectors
Is there an easy fix to the problem?
Merry Xmas and thank you

回答(3 个)

Junaid
Junaid 2011-12-25
Dear I guess if your matrix num after reshaping maintains it dimensions then reshape function should not be a problem. The examples values you have given, i executed following code without any error.
num = [20050103
34200000
10
20050103
34205000
14
20050103
34210000
8
20050103
34215000
11
20050103
34220000
15
20050103
34225000
13
20050103
34230000];
av=reshape(num, 4,length(num)/4); % this is 4 x 5 matrix.
m = mean(av); % col wise sum
mr = mean(av,2); % row wise sum.
I hope I understood your question ?

Walter Roberson
Walter Roberson 2011-12-25
MATLAB cannot have columns of different lengths in a numeric matrix, and so reshape() can only be used when the initial number of elements matches the requested number of full rows times the requested number of full columns.
You can pad the original vector with a value that you then program to be ignored afterwards. For example, you could pad your vector with NaN and then use nanmean() from one of the toolboxes or from the user contribution http://www.mathworks.com/matlabcentral/fileexchange/6837

Andrei Bobrov
Andrei Bobrov 2011-12-26
try this cod. Use function nanmean by Statistic Toolbox
num = [10 14 8 11 15 13 7].';
n = 4;
num1 = [num; NaN(n-rem(numel(num),n),1)];
out = nanmean(reshape(num1,n,[])).';
variant without use nanmean
n = 4;
n1 = numel(num);
n2 = ceil(n1/n);
num1 = NaN(n,n2);
num1(1:n1) = num;
out = arrayfun(@(x)mean(num1(~isnan(num1(:,x)),x),(1:n2)');

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by