"I created a function that takes 5 elements of an array, calculates the mean and puts the value into another array. It does that for the next 5 elements and so on"
@Anahita Mahmoodi: Your code does not get every sequential block of five elements. This is easy to check, by measuring the length of each block in the loop:
A = [5146.75; 4683.60; 5011.46; 4831.69; 4836.99; 5107.30; 3356.42; 4973.96; 4253.51; 4885.74; 4949.31; 3308.19; 2960.01; 3181.87; 2738.16; 2393.43; 1904.20; 1703.93; 2834.68; 3085.89]
x = zeros((numel(A)/5),1);
b = 0;
while b <= (numel(x) -1)
a = b*5 + 1;
tmp = (A(a,1)):A((a+4),1);
disp(numel(tmp))
x(b+1,1)= mean(tmp);
b=b+1;
end
which prints this:
Definitely not blocks of five. The first four iterations have no elements at all in them. In fact you are not getting blocks of elements of A at all. Lets have look at what this line of your code is really doing:
x(b+1,1)= mean((A(a,1)):A((a+4),1))
Lets take b=0 as our example:
>> b = 0;
>> a = b*5 + 1
a =
1
>> (A(a,1))
ans =
5146.8
>> A((a+4),1)
ans =
4837
>> (A(a,1)):A((a+4),1)
ans =
Empty matrix: 1-by-0
Your code actually applies the colon operator to the values of A, rather than to the indices which is what you should be doing:
>> A(a:a+4,1)
ans =
5146.8
4683.6
5011.5
4831.7
4837
This is why it is important for beginners to actually check their code instead of just relying on their imagination. What code is really doing is more important that what you imagine it is doing. So you need to learn to check it.
Rather than doing this in a loop, a much better solution is to learn how to use MATLAB and split the values using mat2cell or accumarray: >> A = [5146.75; 4683.60; 5011.46; 4831.69; 4836.99; 5107.30; 3356.42; 4973.96; 4253.51; 4885.74; 4949.31; 3308.19; 2960.01; 3181.87; 2738.16; 2393.43; 1904.20; 1703.93; 2834.68; 3085.89];
>> idx = ceil((1:numel(A))/5);
>> B = accumarray(idx(:),A,[],@mean)
B =
4902.1
4515.4
3427.5
2384.4
Best Answer