how to take random words from a sting matrix

i have a 1x9 matrix full of words, i want to randomly take 5 of them and put them into another matrix of 1x5 how would i go about this?
id also like to do something similar where i take a random number from a 1x20 array and asign it to a variable

Answers (2)

Words = ["a","1","x","9","string","matrix","full","of","words"]
Words = 1×9 string array
"a" "1" "x" "9" "string" "matrix" "full" "of" "words"
idx = randperm(numel(Words))
idx = 1×9
3 9 1 2 7 4 8 5 6
inOtherWords = Words(idx(1:5))
inOtherWords = 1×5 string array
"x" "words" "a" "1" "full"

5 Comments

That's one way to select elements without replacement (think dealing cards from a deck.) For selection with replacement (rolling a bunch of dice) use randi.
Words = ["a","1","x","9","string","matrix","full","of","words"]
Words = 1×9 string array
"a" "1" "x" "9" "string" "matrix" "full" "of" "words"
idx = randi(numel(Words), 5, 5)
idx = 5×5
8 5 1 9 8 4 5 7 3 5 4 1 4 3 8 9 5 9 6 7 4 8 5 3 9
inOtherWords = Words(idx)
inOtherWords = 5×5 string array
"of" "string" "a" "words" "of" "9" "string" "full" "x" "string" "9" "a" "9" "x" "of" "words" "string" "words" "matrix" "full" "9" "of" "string" "x" "words"
omg thank you so much this was amazingly helpful
is there a find function for these word values i cant seem to use the usual
if any( outputlootpool(1,:) == "coin" )
coinfound=randi(40)
end
im trying to check if this random matric has a cirtain word and if yes give another variable a random number
@finley: What seems to be the problem?
outputlootpool = ["ruby","coin";"cash","gold"]
outputlootpool = 2×2 string array
"ruby" "coin" "cash" "gold"
any( outputlootpool(1,:) == "coin" )
ans = logical
1
ismember("coin", outputlootpool(1,:))
will return a single true / false value indicating whether "coin" is present
ismember(outputlootpool(1,:), "coin")
will return a vector the size of outputlootpool(1,:) indicating whether each one is "coin"

Sign in to comment.

"id also like to do something similar where i take a random number from a 1x20 array and asign it to a variable"
Try this:
yourVector = rand(1, 20) % Create sample data.
yourVector = 1×20
0.6875 0.6995 0.3919 0.9147 0.6881 0.4603 0.1065 0.1771 0.1242 0.5258 0.4778 0.6885 0.1576 0.3665 0.4577 0.1335 0.3837 0.7527 0.8594 0.3780
randomIndex = randi(numel(yourVector), 1)
randomIndex = 2
yourVariable = yourVector(randomIndex)
yourVariable = 0.6995

Products

Asked:

on 18 Jan 2024

Commented:

on 19 Jan 2024

Community Treasure Hunt

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

Start Hunting!