how to take random words from a sting matrix

10 views (last 30 days)
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)

Voss
Voss on 18 Jan 2024
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
Voss
Voss on 19 Jan 2024
@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
Walter Roberson
Walter Roberson on 19 Jan 2024
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.


Image Analyst
Image Analyst on 18 Jan 2024
"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

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!