How to write a program that will randomly return any one of the given statements

1 次查看(过去 30 天)
Statement1=He uses Nokia
Statement2=He uses Iphone
Statement3=He uses Samsung
Statement4=He uses Motorola
Statement5=He uses Intex
.
.
.
.
Statement50=He uses Dell
Help me to write a program. The program should return one statement randomly from given fifty statements. And with every run, it must give a different statement.

采纳的回答

Birdman
Birdman 2018-3-26
编辑:Birdman 2018-3-26
Firstly, do not dynamically create variables. There has been a lot of discussion going on about this topic, so you might want to read them.
Secondly, consider the following approach for your first five statements:
Statement(1)={'He uses Nokia'};
Statement(2)={'He uses Iphone'};
Statement(3)={'He uses Samsung'};
Statement(4)={'He uses Motorola'};
Statement(5)={'He uses Intex'}
randsample(Statement,1)
randsample will return a random statement each time it is run. Hope this helps.
  1 个评论
Stephen23
Stephen23 2018-3-26
编辑:Stephen23 2018-3-26
Simpler way to define that cell array:
Statement{1} = 'He uses Nokia';
Statement{2} = 'He uses Iphone';
...
or
Statement = {...
'He uses Nokia',...
'He uses Iphone',...
...
};

请先登录,再进行评论。

更多回答(1 个)

Jim Riggs
Jim Riggs 2018-3-26
编辑:Jim Riggs 2018-3-26
First, I agree with Birdman, use a single list of values, not N different variables.
I would solve this problem based on creating a "shuffle" routine that will generate a random sequence from 1 to n. Then, on each iteration, simply return the next value in the randomized sequence.
Lout = suffle(N)
Lout is a randomized sequence from 1 to N. The shuffle function works as follows:
First, creat an ordered list from 1 to N
List=linspace(1,N,N)
loop from i=1 to N
on the first pass, select a random number from 1 to N, and copy the sorted to the randomized list;
k = ceil(rand*N) % k is the random index
Lout(i) = List(k) % i is the loop index
now remove List(k) from the sorted list (so that it will not be re-used) by copying
for m=k:N-1
List(m)=List(m+1)
end
now reduce N by 1, and continue. If you started with N=50, N is now 49 and you go back to the start of the loop. When done, you have a randomized sequence of N integers. The whole shuffle function looks like this:
function Lout = shuffle(N)
List=linspace(1,N,N); % create a list from 1 to N
Lout=zeros(1,N); % Lout will be the randomized list
for i=1:N;
k=ceil(rand*N); % k is the random index
Lout(i)=List(k); % i is the loop index
% now remove the used element from the sorted list
if k<N
for m=k:N-1
List(m) = List(m+1)
end
end
i=i+1;
N=N-1;
end
Use Lout as the index values to pull random values from your original list.

类别

Help CenterFile Exchange 中查找有关 Filter Banks 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by