Octave解释循环变量有何不同?

时间:2018-03-29 06:40:29

标签: variables for-loop octave

有人可以解释为什么会这样吗

disp(sprintf('Value of i = %d\n', i));

disp(sprintf('Value of i = %d\n', i**i));在下面的代码中有不同的解释!

octave:1> load monk.dat 
octave:2> whos
Variables in the current scope:

   Attr Name        Size                     Bytes  Class
   ==== ====        ====                     =====  ===== 
        x          10x10                       800  double

Total is 100 elements using 800 bytes

octave:3> for i=x(:,1),
> disp(sprintf('Value of i = %d\n', i));
> end;
Value of i = 0.330077
Value of i = 0.00601253
Value of i = 0.0864004
Value of i = 0.145695
Value of i = 0.999297
Value of i = 0.170224
Value of i = 0.609515
Value of i = 0.435406
Value of i = 0.454971
Value of i = 0.153091

octave:4> for i=x(:,1),
> disp(sprintf('Value of i = %d', i**i));
> end;
error: can't do A ^ B for A and B both matrices

1 个答案:

答案 0 :(得分:0)

for循环迭代给定矩阵的列。遗憾的是,这是隐藏的,因为这里的sprintf函数重复模板,直到它耗尽给定的数据。请考虑以下事项:

>> for i=(1:5)', i, end
i =
   1
   2
   3
   4
   5

>> for i=(1:5), i, end
i =  1
i =  2
i =  3
i =  4
i =  5

正如您所看到的,在第一种情况下,使用列向量,它只循环一次,i等于完整列向量。在第二种情况下,它为行向量中的每个元素循环一次。

您没有注意到这一点:

>> sprintf('Value of i = %d\n', (1:5))
ans = Value of i = 1
Value of i = 2
Value of i = 3
Value of i = 4
Value of i = 5

sprintf重复模板5次,对第二个参数中的每个元素重复一次。