Matlab: Looping through an array

288 views Asked by At

This is my one dimensional array A. containing 10 numbers

A = [-8.92100000000000 10.6100000000000 1.33300000000000 ...
     -2.57400000000000 -4.52700000000000 9.63300000000000 ...
     4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000];

I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8

  1. (a(1)+a(2))/2 - value stored in one block of a matrix say m= zeros(10)
  2. then (a(1)+a(2)+a(3)+a(4))/4 ------ mean-----
  3. then (a(1)+a(2)..... a(8))/8

then shift index;

  1. (a(2)+a(3))/2; - mean
  2. (a(2)+a(3)+a(4)+a(5))/4
  3. (a(2)+a(3)...a(9))/8

SO basically 2^n length interval

1

There are 1 answers

12
Santhan Salai On BEST ANSWER

You could do this using conv without loops

avg_2 = mean([A(1:end-1);A(2:end)])

avg_4 = conv(A,ones(1,4)/4,'valid')

avg_8 = conv(A,ones(1,8)/8,'valid')

Output for the sample Input:

avg_2 =
0.8445    5.9715   -0.6205   -3.5505    2.5530    6.9475   10.6100   12.5635    6.4600

avg_4 =
0.1120    1.2105    0.9662    1.6985    6.5815    9.7555    8.5350

avg_8 =
3.3467    5.4830    4.7506

Finding Standard Deviation for an example (std_4)

%// each 1x4 sliding sub-matrix is made a column
%// for eg:- if A is 1x6 you would get 1-2-3-4, 2-3-4-5, 3-4-5-6 each as a column
%// ending with 3 columns. for 1x10 matrix, you would get 7 columns
reshaped_4 = im2col(A,[1 4],'sliding');    %// change 4 to 2 or 8 for other examples

%// calculating the mean of every column
mean_4 = mean(reshaped_4);

%// Subtract each value of the column with the mean value of corresponding column
out1 = bsxfun(@minus,reshaped_4,mean_4);

%// finally element-wise squaring, mean of each column 
%// and then element-wise sqrt to get the output.
std_4 = sqrt(mean(out1.^2))

Output for the sample Input:

std_4 =

7.0801    5.8225    5.4304    5.6245    7.8384    4.5985    5.0906

Full code for OP

clc;
clear;
close all;

A = [-8.92100000000000 10.6100000000000 1.33300000000000 ...
     -2.57400000000000 -4.52700000000000 9.63300000000000 ...
     4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000];

reshaped_2 = im2col(A,[1 2],'sliding'); %// Length Two 
mean_2 = mean(reshaped_2); 
out1 = bsxfun(@minus,reshaped_2,mean_2); 
std_2 = sqrt(mean(out1.^2)) 
reshaped_4 = im2col(A,[1 4],'sliding'); %// Four 
mean_4 = mean(reshaped_4); 
out1 = bsxfun(@minus,reshaped_4,mean_4); 
std_4 = sqrt(mean(out1.^2)) 
reshaped_8 = im2col(A,[1 8],'sliding'); %// Eight 
mean_8 = mean(reshaped_8); 
out1 = bsxfun(@minus,reshaped_8,mean_8); 
std_8 = sqrt(mean(out1.^2))