generating random values within a range with condition

7 Ansichten (letzte 30 Tage)
Austin
Austin am 1 Okt. 2013
Kommentiert: Austin am 2 Okt. 2013
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 Kommentare
Azzi Abdelmalek
Azzi Abdelmalek am 1 Okt. 2013
Posting a code as an image is not useful, we can not test it
Roger Stafford
Roger Stafford am 1 Okt. 2013
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Image Analyst
Image Analyst am 1 Okt. 2013
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.

Weitere Antworten (0)

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by