Trial and Error
13 次查看(过去 30 天)
显示 更早的评论
Can someone give a example of Matlab codes perform 'trial and error' it will assume certain value , get the answer , error check , in case of suitable result stop the loop ?
0 个评论
回答(3 个)
the cyclist
2012-2-12
Here is a simple example. Is this what you mean by "trial and error"?
x = 100;
while x > 1
x = x-1;
end
x
0 个评论
Image Analyst
2012-2-12
Make an array with your "certain values" like, for example, choices=[1,2,3,4,100,200,1000] or whatever. Then use randi() to pick an index from that at random. Break out if you selected the value to stop at.
% Define the "certain values"
choices=[1,2,3,4,100,200,1000]
% Tell it to stop if choice #4 is chosen.
choiceToStopAt = choices(4);
for k = 1 : 200
randomIndex = randi(length(choices), 1);
selectedChoice = choices(randomIndex);
fprintf('At experiment %d, randomIndex = %d, selected choice = %d\n',...
k, randomIndex, selectedChoice);
if selectedChoice == choiceToStopAt
fprintf('Stopping because we selected %d\n', choiceToStopAt)
break;
end
end
In the command window:
choices =
1 2 3 4 100 200 1000
At experiment 1, randomIndex = 5, selected choice = 100
At experiment 2, randomIndex = 1, selected choice = 1
At experiment 3, randomIndex = 6, selected choice = 200
At experiment 4, randomIndex = 4, selected choice = 4
Stopping because we selected 4
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!