如何继续循环直到达到预先建立的置信区间?
How to continue a loop until reaching a pre-established confidence interval?
我有一个 for
这种类型的循环:
n = 10;
all_values = cell (n,1);
for i = 1:n
do something (series of operations)
all_values{i} = [result1; result2]
end
现在,我想将其转换为 while
- 循环(因此独立于 n
),当达到两个连续迭代结果之间的置信区间时结束,在具体时间:
result1 {n,1}(1,1) - result1 {n-1,1}(1,1) <= 0.1
我该怎么做?
我不知道您为什么要使用单元格,但使用常规数组很简单。这里我随机计算
all_values = zeros(2,1);
result1 = 100;
while result1 - all_values(end-1,1) > 0.1
result1 = rand;
result2 = rand;
all_values = [all_values [result1; result2]];
end
然后您将值存储在每一列中。但即使这样也不是好的做法,因为您的数组正在不受控制地增长。
我建议定义最大迭代次数并初始化所有内容。如果不需要,您可以稍后删除不需要的列。
你的循环最直接的翻译是:
n = 3;
%// assumes first two values are already set
while ~(result1 {n-1,1}(1,1) - result1 {n-2,1}(1,1) <= 0.1)
%// do something (series of operations in which result1 {n,1} is set)
all_values{n} = [result1; result2];
n = n + 1;
end
或
n = 2;
%// assumes first value is already set
while n == 2 || ~(result1 {n-1,1}(1,1) - result1 {n-2,1}(1,1) <= 0.1)
%// do something (series of operations in which result1 {n,1} is set)
all_values{n} = [result1; result2];
n = n + 1;
end
我有一个 for
这种类型的循环:
n = 10;
all_values = cell (n,1);
for i = 1:n
do something (series of operations)
all_values{i} = [result1; result2]
end
现在,我想将其转换为 while
- 循环(因此独立于 n
),当达到两个连续迭代结果之间的置信区间时结束,在具体时间:
result1 {n,1}(1,1) - result1 {n-1,1}(1,1) <= 0.1
我该怎么做?
我不知道您为什么要使用单元格,但使用常规数组很简单。这里我随机计算
all_values = zeros(2,1);
result1 = 100;
while result1 - all_values(end-1,1) > 0.1
result1 = rand;
result2 = rand;
all_values = [all_values [result1; result2]];
end
然后您将值存储在每一列中。但即使这样也不是好的做法,因为您的数组正在不受控制地增长。
我建议定义最大迭代次数并初始化所有内容。如果不需要,您可以稍后删除不需要的列。
你的循环最直接的翻译是:
n = 3;
%// assumes first two values are already set
while ~(result1 {n-1,1}(1,1) - result1 {n-2,1}(1,1) <= 0.1)
%// do something (series of operations in which result1 {n,1} is set)
all_values{n} = [result1; result2];
n = n + 1;
end
或
n = 2;
%// assumes first value is already set
while n == 2 || ~(result1 {n-1,1}(1,1) - result1 {n-2,1}(1,1) <= 0.1)
%// do something (series of operations in which result1 {n,1} is set)
all_values{n} = [result1; result2];
n = n + 1;
end