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

조회 수: 11 (최근 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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by