How do I randomly assign two integers to an array of strings?

3 ビュー (過去 30 日間)
Claire
Claire 2013 年 7 月 7 日
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!

採用された回答

Jim Hokanson
Jim Hokanson 2013 年 7 月 7 日
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;
  1 件のコメント
Claire
Claire 2013 年 7 月 7 日
Thank you that worked perfectly. One last question: is there a way to then display the string with its corresponding value of 1 or 2?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by