can we check a condition at the end of a loop?
Show older comments
Hi everyone.
I am trying to create a new matrix. In each row, it isn't allowed to have two of the same numbers next to each other (more than 1x).
So for this, I created a new empty matrix and then I wanted to create a while loop for each of the rows and input them in the zero matrix.
So far I have something like :
%creates an empty matrix B
B = zeros (6,32);
%creates a row vector with numbers from 1 to 8
rowvector = 1:8;
%creates a vector that copies the rowvector above 4 times
vector = repmat (rowvector, 1, 4);
%creates the first row for vector B
Brow1 = vector (randperm (length(vector)))
%counts how many times the same number is listed twice in a row
count = sum(diff(Brow1)==0 & diff([NaN, Brow1(1:end-1)])~=0)
----here is where I struggle... I want to create a while loop that looks into Brow1 and if count <= 1 then it inputs it into the matrix B, but I am not sure how to go about this. Would you be able to help me with this ?
Accepted Answer
More Answers (1)
Andrei Bobrov
on 22 Jun 2019
Edited: Andrei Bobrov
on 22 Jun 2019
B = sort(repmat(1:8,6,4),2);
[m,n] = size(B);
for i0 = 1:m
while any(~diff(B(i0,:)))
B(i0,:) = B(i0,randperm(n));
end
end
Categories
Find more on Matrix Indexing 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!