How to randomise numbers in a vector?

24 次查看(过去 30 天)
Dear all,
Suppose I have this vector x= [1;2;3;4];
How can I randomise it? (i.e. create different combinations of 1, 2, 3 and 4)
Thank you very much in advance, Bianca

采纳的回答

Jan
Jan 2016-12-17
编辑:Jan 2016-12-17
See doc randperm:
x = [1;2;3;4]
y = x(randperm(numel(x)))
If this is time-critical, use FEX: Shuffle .
  5 个评论
Bianca Elena Ivanof
Bianca Elena Ivanof 2016-12-18
编辑:Bianca Elena Ivanof 2016-12-18
Dear Jan,
Thank you very much for your help. The second option works wonders! I am trying to randomise the subconditions of the main conditions of my experiment - in order for me to do so, there is one last step I need to figure out. I understand if this post is becoming a bit too lengthy for you but, if not, could you please be so kind as to help me understand one more thing? If yes, please see the file attached.
counterbalancing(:,1)= participant ID
counterbalancing(:,2)= speed levels (1, 2, 3)
counterbalancing(:,3)= conditions (1, 2, 3, 4) per speed level
What I am trying to do is, for every speed level (column 2) per participant (column 1), to randomise the 4 speed level subconditions (column 3) - i.e. to randomise the first 4 rows containing 1, 2, 3, 4 and then the next 4 rows containing 1, 2, 3, 4 and so on and so forth, until the end of the matrix. I very vaguely remember there is a simple of doing computations on every n rows at a time, which doesn't require for loops or anything of the sort.
Jan
Jan 2016-12-19
编辑:Jan 2016-12-19
Y = reshape(X(:, 3), 4, [])
YS = Shuffle(Y, 1); % Mix columns
X(:, 3) = YS(:);

请先登录,再进行评论。

更多回答(1 个)

Andrei Bobrov
Andrei Bobrov 2016-12-17
编辑:Andrei Bobrov 2016-12-17
Hi Elena!
One way:
x= [1 1; 1 2; 1 3; 1 4]
[~,ii] = sort(rand(size(x,1),1));
out = x(ii,:);
or just
out = x(randperm(size(x,1)),:);
  2 个评论
Jan
Jan 2016-12-18
编辑:Jan 2016-12-18
randperm uses the Fisher-Yates shuffle now (as FEX: Shuffle), which is more accurate than SORT(RAND). The later is a stable sort, so if two elements replied by RAND are equal (unlikely, but not impossible) the sorting order is not random. If you e.g. have to shuffle a vector of 2^52 elements, uuhm, well... Who cares.

请先登录,再进行评论。

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by