Referencing and extracting with conditions
Afficher commentaires plus anciens
Hello everyone,
I have 2 matrices.
First, is called combomatrix of 3 columns, combinations that sum to 56 , and this is a 35640 X 3 matrix . Ther are no zeros.
Second, is letters combination of a,b and c.
parts = [a, b, a ;
b, b, c ;
c, a, b ;
b, c, b ;
a, a, b]
A maximum value associated with each letter is a = 20, b = 30, c = 35. For each row of parts matrix, I want to extract rows from thecombo matrix in the follwing manner:
For example, row 2 of parts = [b,b,c]. Referencing this vector into the combo matrix, I want to extract rows, with column 1 values are 30 or lower AND column 2 values 30 or lower AND column 3 values 35 or lower as that corresponds to the maximums for the letters associated with the vector.
How do I code for this?
Thank you for your time.
Réponse acceptée
Plus de réponses (2)
Image Analyst
le 10 Déc 2020
Try this:
% Create matrix with all combinations of where 3 numbers add to 56
combomatrix = zeros(1, 3);
row = 1;
for k1 = 1 : 56
for k2 = 1 : 56
for k3 = 1 : 56
if k1+k2+k3 == 56
combomatrix(row, :) = [k1, k2, k3];
row = row + 1;
end
end
end
end
% Create part2.
a = 20;
b = 30;
c = 35;
parts = [a, b, a ;
b, b, c ;
c, a, b ;
b, c, b ;
a, a, b]
% Let's get row 2
row2 = parts(2, :)
% Get indexes where first column is less than row2(1).
col1Indexes = combomatrix(:, 1) <= row2(1);
% Get indexes where second column is less than row2(2).
col2Indexes = combomatrix(:, 2) <= row2(2);
% Get indexes where third column is less than row2(3).
col3Indexes = combomatrix(:, 3) <= row2(3);
% Find out where all three conditions are true.
goodRows = col1Indexes & col2Indexes & col3Indexes;
% Extract those rows from combomatrix
goodMatrix = combomatrix(goodRows, :)
You get good matrix, a matrix of 695 rows.
2 commentaires
klb
le 11 Déc 2020
Modifié(e) : Image Analyst
le 11 Déc 2020
Image Analyst
le 11 Déc 2020
Right now, no answer is Accepted. Did you unaccept it? Please "Accept" your favorite answer. You can also "Vote" for the answer you accepted, plus Vote for any additional other answers to give all people who helped you "reputation points".
N=size(parts,1);
result=cell(N,1);
for i=1:N
rows=all(combomatrix<=parts(i,:),2);
result{i}=combomatrix(rows,:);
end
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!