Where you are struggling is in explaining what you want to do. Giving an example is often a good idea. That is, give an example of a row that fails your criteria. Then one that is satisfactory.
As far as counting the number of times an element is listed consecutively in a row, then it would seem satisfactory to just use
count = sum(diff(Brow1)==0);
Even simpler is to just for a logical nagation of the vector.
The secondary clause in your test does not seem to be pertinent. As I wrote it, this just counts the number of events where an element is equal to the element that follows it. As long as that never exceeds 1, then you are ok. However, that is not terribly clear it is what you are asking for, since your question is fairly confusing.
V0 = repmat(1:8,1,4);
V = V0(randperm(32))
V =
Columns 1 through 25
4 3 8 4 5 5 2 6 8 6 6 4 1 1 8 5 3 4 2 3 7 8 7 6 1
Columns 26 through 32
2 7 1 5 3 7 2
sum(~diff(V))
ans =
3
So there are 3 such events in this sample. They are located at elements [5,10,13] with the next element in each case identical.
find(~diff(V))
ans =
5 10 13
Your requirement is that can happen at most once, although zero such events is apprently ok? Is a count of zero such events preferable? BE CLEAR!!!!!
Anyway, it seems to me to be simplest to
nrows = 6;
V0 = repmat(1:8,1,4);
nv = numel(V0);
B = zeros(nrows,nv);
for i = 1:nrows
V = V0(randperm(nv));
loc = find(~diff(V));
while numel(loc) > 1
newloc = setdiff(1:nv,loc);
newloc = randperm(numel(newloc),numel(loc));
V([loc,newloc]) = V([newloc,loc]);
loc = find(~diff(V));
end
B(i,:) = V;
end
In the above loop, you will find the internal while loop actually only runs very few times, because most of the time the swap results in few mishaps on the next pass through the loop.
As well, I could surely have been more intelligent about how I choose a location to swap an element into, but why bother to make something that is already efficient, slightly more so? That at the cost of more complex code? Don't pre-optimize your code unless it is a problem.
B'
ans =
6 5 5 7 1 7
4 4 3 3 5 1
1 8 1 6 7 5
3 2 3 7 1 3
7 3 6 8 3 4
4 6 7 5 6 6
5 2 6 3 3 5
2 5 2 6 5 6
4 1 5 5 6 2
6 7 1 2 2 7
7 7 5 4 4 5
1 1 7 2 2 4
7 7 3 7 7 5
2 1 8 3 7 8
5 5 4 1 4 1
3 8 6 8 5 3
1 6 8 6 3 6
5 4 7 5 4 8
8 8 2 1 1 1
2 5 3 4 6 7
8 2 1 1 8 3
4 3 2 3 4 4
8 1 6 4 8 4
3 6 4 4 5 2
2 4 8 2 2 1
6 7 2 7 6 6
1 6 1 8 2 3
6 8 4 5 8 2
5 3 7 8 1 7
3 2 4 1 7 8
7 3 7 6 3 2
8 4 5 2 8 8
>> sum(~diff(B,[],2),2)
ans =
0
1
0
1
1
1
It would seem the above set should be satisfactory. But I am not at all sure.
0 件のコメント
サインイン to comment.