# Problem relating to mathematical expression

1 view (last 30 days)
Tino on 28 May 2020
Commented: Tino on 1 Jun 2020
Hello I have a set of 10 random variables using a window length of k =5
0.1, 0.2, 0.4, 0.5, 0.4, 0.6, 0.6, 0.6, 0.2, 0.3
first window size ( 0.1, 0.2 ,0.4, 0.5, 0.4)
first answer = (0.1 + 0.2 + 0.4 + 0.5 + 0.4)/5 = 0.32
second answer =( 0.2 + 0.4 + 0.5 + 0.4 )/4 = 0.375
third answer = (0.4 + 0.5 + 0.4)/3 = 1.3
fourth answer = (0.5 + 0.4)/2 =0.45
fifth answer = 0.4/1 = 0.4
second window size (0.6,0.6, 0.6, 0.2, 0.3)
first answer = 0.6 + 0.6 + 0.6 + 0.2 + 0.3 /5 = 0.46
second answer = 0.6 + 0.6 + 0.2 + 0.3/4 = 0.425
third answer = 0.6 + 0.2 + 0.3/3 = 0.367
fourth answer = 0.2 + 0.3 /2 = 0.25
How do I compute this process in matlab
Your response will be greatly appreciated
total answer is then 0.32, 0.375, 1.3, 0.45, 0.4 , 0.46, 0.425, 0.367, 0.25, 0.3
if the last remaining number is not up to the window size then we use the total number remaining as the window size.
for instance we have 4 4 4 4 2 2 2
if we take the window length of 5 (4 4 4 4 2)
the remain ( 2, 2) will be computed using the window length of 2

Ameer Hamza on 28 May 2020
Edited: Ameer Hamza on 28 May 2020
Try this
x = [0.1, 0.2, 0.4, 0.5, 0.4, 0.6, 0.6, 0.6, 0.2, 0.3];
n = numel(x);
k = 5;
if round(n/k)==n/k
split = mat2cell(x, 1, repmat(k, 1, floor(numel(x)/k)));
else
split = mat2cell(x, 1, [repmat(k, 1, floor(numel(x)/k)) mod(n, k)]);
end
helpFun = @(x) {fliplr(cumsum(fliplr(x))./(1:numel(x)))};
split_mean = cellfun(helpFun, split);
split_mean = [split_mean{:}]
Tino on 1 Jun 2020
Thank you Ameer. Greatly appreciated

Are Mjaavatten on 28 May 2020
Ameer's answer is correct, of course. Here is another approach, without the elegant Matlab functions:
N = 5; % Max window size
% Throw in a few extra elements, to test:
x = [0.1, 0.2, 0.4, 0.5, 0.4, 0.6, 0.6, 0.6, 0.2, 0.3, 0.5, 0.3];
L = length(x);
result = zeros(1,L);
last = N;
first = 0;
while first < L
while last > first
first = first + 1;
result(first) = sum(x(first:last))/(last-first + 1);
end
last = min(last + N, L);
end
disp(result);
Tino on 1 Jun 2020
Thank you Are

### Categories

Find more on Logical in Help Center and File Exchange

R2019a

### Community Treasure Hunt

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

Start Hunting!

Translated by