To pick a number randomly
1 次查看(过去 30 天)
显示 更早的评论
Can some one help in picking a number from a matrix for example i have matrix of the form A=[1 2 3 4 5; 6 6 7 5 8 ; 12 4 5 6 9] and i require to pick only one element randomly from the matrix but should not be the same element every time.
0 个评论
采纳的回答
Andrei Bobrov
2012-9-11
编辑:Andrei Bobrov
2012-9-11
try this is code
A=[1 2 3 4 5; 6 6 7 5 8 ; 12 4 5 6 9];
a = unique(A);
b = a(histc(A(:),a) < 2);
idx = randperm(numel(b));
out = b(idx(1));
更多回答(1 个)
Rene
2012-9-11
编辑:Rene
2012-9-11
The answer of andrei does not give a truly random number since he uses the unique command.
This will:
A=[1 2 3 4 5; 6 6 7 5 8 ; 12 4 5 6 9];
B = round((length(A(:))-1)*rand+1);
A(B)
ps. as far as rand returns a truly random number
2 个评论
Andrei Bobrov
2012-9-12
编辑:Andrei Bobrov
2012-9-12
A2 = reshape(A',[],1);
out = A2(randperm(numel(A),1));
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!