pick a random text with different probability in matlab

One possible solution is to use the rand function to generate a random number between 0 and 1, and then use if statements to decide the output based on different probability ranges. Here's an example code:

main.m
% Define the texts and their respective probabilities
texts = {'text1', 'text2', 'text3'};
probs = [0.3, 0.5, 0.2];

% Generate a random number
r = rand();

% Use if statements to pick the output text based on probability ranges
if r < probs(1)
    output = texts{1};
elseif r < probs(1) + probs(2)
    output = texts{2};
else
    output = texts{3};
end

% Print the output text
disp(output);
393 chars
19 lines

In this example, we have three texts ('text1', 'text2', and 'text3') with different probabilities (0.3, 0.5, and 0.2). The code generates a random number r between 0 and 1 using rand(), and then uses if statements to decide the output text based on the probability ranges. The first text has a probability range of [0, 0.3), the second text has a range of [0.3, 0.8), and the third text has a range of [0.8, 1]. Finally, the code prints the output text using disp().

related categories

gistlibby LogSnag