How do I randomly assign two integers to an array of strings?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have an array of strings and would like to randomly assign either a "1" or a "2" to each string. I need an equal amount of strings assigned to each integer.
I am new to matlab so I would appreciate any help. Thanks!
0 Kommentare
Akzeptierte Antwort
Jim Hokanson
am 7 Jul. 2013
I like to think of the solution as involving grouping the strings into two different groups. One way of doing this is to sort an array of random numbers the same size as your group. Indices whose random numbers are less than the mean will go into one group, and those greater, into another.
For example consider 4 strings, for which we generate 4 random numbers: 0.4 0.2 0.1 0.5 The two middle numbers are the smallest 2 numbers, and the 1st and last are the largest 2 numbers. When sorting you can ask for an index output which will tell you where the sorted number is in the original: [3 2 1 4] Using this index output, you can assign your output of 1's and 2's.
The code: N = 100; %# of strings [~,I] = sort(rand(1,N)); %Make sure to ask for the indices ...
string_number = ones(1,N);
half_n = floor(N/2); %Ensure integer value
string_number(I(1:half_n)) = 2;
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Characters and Strings 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!