pick a random value out of text in matlab

To pick a random value out of text in Matlab, you can first split the text into separate words using the split function, which returns a 1-by-n string array where each element is a word in the original text.

Then, you can generate a random integer within the range of indices of this string array using the randi function, and use that integer to index into the array and select a random word.

Here's an example:

main.m
text = "This is some sample text with several words";
words = split(text);
random_word_index = randi([1 length(words)]);
random_word = words(random_word_index);
disp(random_word);
180 chars
6 lines

This code will output a random word from the input text.

Note that the randi function returns a uniformly distributed integer between the specified minimum and maximum values, inclusive. In this case, we set the minimum to 1 and the maximum to the length of the words array, so that the random integer will be a valid index into the array.

gistlibby LogSnag