Matlab:通过数组循环

时间:2015-06-15 17:39:57

标签: matlab loops for-loop while-loop do-while

这是我的一维数组A。包含10个数字

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

我希望循环能够像这样经历; (计算平均间隔) - 间隔长度为2,4,8

  1. (a(1)+a(2))/2 - 存储在矩阵的一个块中的值,表示m =零(10)
  2. 然后(a(1)+a(2)+a(3)+a(4))/4 ------意思是-----
  3. 然后(a(1)+a(2)..... a(8))/8
  4. 然后换班指数;

    1. (a(2)+a(3))/2; - 意思是
    2. (a(2)+a(3)+a(4)+a(5))/4
    3. (a(2)+a(3)...a(9))/8
    4.   

      SO基本上是2 ^ n长度间隔

1 个答案:

答案 0 :(得分:3)

您可以使用conv无循环

来执行此操作
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')

示例输入的输出:

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

查找示例(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))

示例输入的输出:

std_4 =

7.0801    5.8225    5.4304    5.6245    7.8384    4.5985    5.0906

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))
相关问题