필터 지우기
필터 지우기

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