0

我使用以下函数生成随机值:

 P = floor(6*rand(1,30)+1)

然后,使用T=find(P==5),我得到了结果所在的值5并将它们存储在T. 输出是:

T =

   10   11   13   14   15   29

T现在,我想计算使用的平均值,mean(T)但它给了我以下错误:

错误:平均值(29):超出界限 1(尺寸为 1x1)(注意:变量“平均值”阴影函数)

我想做的是模拟掷骰子的结果,并计算我第一次得到 5 的结果。然后我想取所有这些时间的平均值。

4

1 回答 1

2

Although you don't explicitly say so in your question, it looks like you wrote

mean = mean(T);

When I tried that, it worked the first time I ran the code but the second and subsequent times it gave the same error that you got. What seems to be happening is that the first time you run the script it calculates the mean of T, which is a scalar, i.e. it has dimensions 1x1, and then stores it in a variable called mean, which then also has dimensions 1x1. The second time you run it, the variable mean is still present in the environment so instead of calling the function mean() Octave tries to index the variable called mean using the vector T as the indices. The variable mean only has one element, whose index is 1, so the first element of T whose value is different from 1 is out of bounds. If you call your variable something other than mean, such as, say, mu:

mu = mean(T);

then it should work as intended. A less satisfactory solution would be to write clear all at the top of your script, so that the variable mean is only created after the function mean() has been called.

于 2021-06-13T21:03:40.857 回答