Sorting Permutation Matrix for Rows With Specific Consecutive Values
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (1)
Arjun
il 6 Set 2024
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 Commenti
Vedere anche
Categorie
Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!