randperm in while loop
5 views (last 30 days)
Show older comments
Hi, I want to achieve the following with my code:
For A(1) I can chose randomly from 1, 2 or 3 - but if A(1) say is equal to 1, then A(2) should be randomly chosen from either 2 or 3, and if A(2) would be say 3, then A(3) = 2. And with A(4) the game starts again. So I wrote the following code - and run it with RandomizeTrials(3,12) - why is it not running?
function [Array] = RandomizeTrials(numberofSeq, lengthofArray)
Array = zeros(1,lengthofArray);
k = 1;
while k < lengthofArray-1
m = k+numberofSeq-1;
Array(k:m) = randperm(numberofSeq,numberofSeq,false);
k+numberofSeq;
end
end
1 Comment
Adam
on 29 Apr 2015
What do you mean by "not running"?
When I run it I get a clear error message which tells me exactly what the problem is which I can consult the randperm help page for to confirm. I assume you can do likewise if you are getting the same error.
Answers (2)
pfb
on 29 Apr 2015
If I get it right, you want a vector A that is "divided" into bunches of 3 consecutive elements. Each of these "bunches" should be a random permutation of the integers 1, 2, 3.
This should be it
A = zeros(3*N);
for k=1:N
A((k-1)*3+(1:3))=randperm(3);
end
You can also create a Nx3 matrix of random permutations, and then possibly "unwind" it to a single vector.
A = zeros(N,3);
for k =1:N
A(k,:)=randperm(3);
end
A = A'; % transpose so that the permutations are along columns
A = A(:); % the columns of A are concatenated into a single column vector
3 Comments
pfb
on 29 Apr 2015
Edited: pfb
on 29 Apr 2015
Hi
(k-1)*3+(1:3)
is the same as
((k-1)*3+1):(k*3)
i.e. the indices
k*3-2, k*3-1, k*3
if k=1 these are 1,2,3; if k=2 these are 4,5,6, and so on... This particular choice is related to the fact that indices start from 1 in matlab.
The second choice above is more or less what Thorsten suggested below, although he did that in two lines, probably for clarity reason.
I thought that
(1:3)+(k-1)*3
was sufficiently clear:
(1:3)
is the vector [1 2 3]. Then I add (k-1)*3, and I use the result as the index for A.
Thorsten
on 29 Apr 2015
Edited: Thorsten
on 29 Apr 2015
In this solution you have a growing array in a loop, which is not the fasted way, but you do not have to fiddle with indices:
N = length_of_array/number_of_sequence;
x = [];
for i=1:N
x = [x randperm(number_of_sequence)];
end
If you insist on preallocation and indices
x = zeros(1, length_of_array);
for i=1:N
i1 = (i-1)*number_of_sequence;
x(i1+1:i1+number_of_sequence) = randperm(number_of_sequence);
end
0 Comments
See Also
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!