Im using randsample to make the program choose a random element from an array,
A=[2 3 4 5];
random=randsample(A,1)
but im getting an error that says 'randsample' requires Statistics and Machine Learning Toolbox.
So how can i make it work, or is there any other way i can make a random selection.

 채택된 답변

Geoff Hayes
Geoff Hayes 2022년 1월 7일

1 개 추천

@Tariq Hammoudeh yes, randsample requires the Statistics and Machine Learning Toolbox. If you just want to choose one random element from this array, you could do something like
A = [2 3 4 5];
randomValue = A(randi(length(A),1));

댓글 수: 6

Tariq Hammoudeh
Tariq Hammoudeh 2022년 1월 7일
편집: Tariq Hammoudeh 2022년 1월 7일
Thank you but i tried that and it didnt really work with my code because my actual code is me reading in external files using readmatrix() then putting the variables of these files into an array. So:
one=readmtarix()
two=readmatrix()
three=readmatrix()
A=[one two three]
x=A(randi(length(A),1))
is it possible to make x select either one or two or three (the variable names for the files)
so that i can use
if x==two
......
Im sorry i thought it would work the same as if it was numbers, so i just gave an example to make it simpler.
one=readmtarix();
two=readmatrix();
three=readmatrix();
A = {one two three};
x = A{randi(length(A))} ;
Now you can test
if x == two
It just isn't a good idea.
Thank you that workds fine because ill just place the ships one by one manually, but can i ask why did this work when we use {} instead of []
Correction, you would need to use
if isequal(x, two)
since we should not assume that the matrices are the same size.
I am having trouble coming up with reasons why you would want to compare entire configuration arrays to other configuration arrays. The information in the configuration file should give you everything you need to place the ships without human intervention, and the only thing that you might have reason to differentiate between them might be to display a small notice such as "Game #182"
y=zeros(1,36)
if isequal(x,one)
y(1)=1;
y(2)=1;
......
But whenever i run the code, all the elements of y stay zero, nothing becomes 1. How can i fix it.
I would say... don't do that.
one=readmtarix();
two=readmatrix();
three=readmatrix();
A = {one two three};
x = randi(length(A));
board_configuration = A{x};
if x == 1
...
elseif x == 2
...
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Software Development Tools에 대해 자세히 알아보기

제품

릴리스

R2021b

태그

Community Treasure Hunt

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

Start Hunting!

Translated by