Scilab:无效的索引

时间:2018-11-29 12:38:37

标签: loops matrix scilab

我尝试计算10个矩阵项的平均值(1:10、2:11、3:12等),然后从这些平均值中创建一个新矩阵。但是,它总是给我无效索引。

A=rand(150,1);
number_of_rows=size(A,1);
for i=1:number_of_rows
  B=mean(A(i:i+9,1),1);
  C(i,:)=B;
end

1 个答案:

答案 0 :(得分:1)

下面的代码就可以做到,对于任何窗口的长度 n:

A = grand(1,40,"uin",0,9)
n = 10;

C = [0 cumsum(A)];
C = (C(n+1:$)-C(1:$-n))/n

结果(样本):

-->     A = grand(1,40,"uin",0,9)
 A  = 
         column 1 to 24
   3.   2.   2.   9.   2.   6.   1.   5.   1.   5.   7.   2.   5.   8.   3.   0.   3.   8.   3.   3.   4.   8.   8.   1.

         column 25 to 40
   4.   2.   0.   8.   5.   8.   5.   3.   7.   3.   1.   8.   8.   0.   0.   4.

-->     n = 10;
-->     C = [0 cumsum(A)];
-->     C = (C(n+1:$)-C(1:$-n))/n
 C  = 
         column 1 to 20
   3.6   4.   4.   4.3   4.2   4.3   3.7   3.9   4.2   4.4   4.2   3.9   4.5   4.8   4.1   4.2   4.4   4.1   4.1   4.3

         column 21 to 31
   4.8   4.9   4.4   4.3   4.5   4.2   4.8   5.6   4.8   4.3   3.9

--> mean(A(1:n))
 ans  =
   3.6

但是,cumsum() 会传播属于 A 的任何 Inf 或 NaN 值。