generating random values within a range with condition
1 次查看(过去 30 天)
显示 更早的评论
i can see this works but which part of my script can i make use of the function "while" so that i dont have to repeat this script again for row 2 to row 7?
or can anyone advise me a more efficient way perform the task? Thank you in advance,your advice would be greatly appreciated.
2 个评论
Roger Stafford
2013-10-1
The "rejection" method you are using has a serious flaw in the cases where the user happens to select a value very close to 3. For example, if 2.95 is chosen, the odds that a row of your randomly selected 'p' would satisfy your condition is one in about fifty billion - to be precise, one in 10^7*factorial(7). That would require a great many rejections on the average before succeeding.
采纳的回答
Image Analyst
2013-10-1
You could do this:
clc;
x = 19; % For example.
% Get sample data.
p = 2.5 + 0.5 * rand(7,7)
% Sum up the rows, going across columns within each row.
sumsOfRows = sum(p, 2)
% Find which rows don't sum up to x or greater.
badRows = find(sumsOfRows < x)
% While loop to replace the bad rows.
while any(badRows)
for row = 1 : length(badRows)
% For each bad row, replace just that row with another try.
p(badRows(row),:) = 2.5 + 0.5 * rand(1,7)
end
% Check again.
sumsOfRows = sum(p, 2)
badRows = find(sumsOfRows < x)
end
By the way, you seem to be getting confused if the sum is to be called A or X, and whether A or X is an integer or a floating point number. Very sloppy & careless problem statement. But now you can't ethically turn it in, so you'll have to come up with your own variant using a while statement. There are other ways to do it though.
更多回答(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!