Referencing and extracting with conditions
3 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
William
on 10 Dec 2020
I think this should work:
function y = combo(combomatrix,row)
% combomatrix is Nx3
% row is integer = row number of parts matrix to use
a = 20; b = 30; c = 35;
parts = [a, b, a ; b, b, c ; c, a, b ; b, c, b ; a, a, b];
y = combomatrix(all(combomatrix <= parts(row,:),2),:);
end
It replace the entries in the 'parts' matrix with their values. Then it select rows of the 'combomatrix' that have all values less than or equal to the selected row of parts.
More Answers (2)
Image Analyst
on 10 Dec 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 Comments
Image Analyst
on 11 Dec 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".
See Also
Categories
Find more on Logical 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!