Sorting Permutation Matrix for Rows With Specific Consecutive Values
조회 수: 1 (최근 30일)
이전 댓글 표시
This code:
n = 3;
v = [1:n 1:n 1:n];
P = nchoosek(v,3);
A = unique(P,'rows');
Produces a Matrix of unique permutations of 1,2 & 3. eg.
1 1 1
1 2 1
1 2 2
1 3 3
etc
I want to sort the resulting rows, eliminating rows with any number of consecutive ones and twos, but NOT consecutive 3's. So in this example (composed of 4 of the 27 rows of A) rows 1 and 3 are no go's but 2 and 4 are fine. I experimented with 'diff(X,n,dim)' but couldn't find an elegant solution.
Thanks in advance.
댓글 수: 0
답변 (1개)
Arjun
2024년 9월 6일
I see that you are trying to generate a matrix with unique rows and in the generated matrix you want to filter out rows with consecutive 1s or 2s but not 3s.
To solve this problem, you can iterate over each row of matrix A and check for consecutive 1s or 2s while allowing consecutive 3s. You can achieve this by using logical operators and logical indexing over rows of the matrix.
We scan over each row of the matrix and then compare each element say “i” with the next element i.e. “i”+1 and check if ele(i) equals ele(i+1) and ele(i) is either 1 or 2. If in a row this condition is satisfied for even one element, we tend to skip the row and move to the next row in order. We maintain a separate “validRows” variable to keep stacking rows which don’t have consecutive 1s or 2s.
Kindly have a look at the code below:
n = 3;
v = [1:n 1:n 1:n];
disp(v);
P = nchoosek(v, 3);
A = unique(P, 'rows');
% Initialize an empty array to store valid rows
validRows = [];
% Iterate over each row of A
for i = 1:size(A, 1)
row = A(i, :);
% Check for consecutive 1s or 2s
if all(~(row(1:end-1) == row(2:end) & (row(1:end-1) == 1 | row(1:end-1) == 2)))
% If no consecutive 1s or 2s, add the row to validRows
validRows = [validRows; row];
end
end
% Display the resulting matrix
disp('Filtered Matrix:');
disp(validRows);
I hope it helps!
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!