I have two tables:
Table 1 has two columns called WP_1 and WP_2.
Table 2 has three columns called WP1, WP2 and WC.
For every pair (row) of WP_1 and WP_2 I want to check if they are within any pair (row) of WP1 and WP2.
If they are within a certain pair of WP1 and WP2, I want to take the value (0 or 1) of WC of that specific pair and print it to a new column in table1 in the same row --> table1.WC
If a pair of WP_1 and WP_2 does not fit any pair of WP1 and WP2 I want to print the value '2' in that specific line of table1.WC.
Here is an example of how I want it to look like:
what table1.Wc should look like after running the script
Explanation:
WP_1 and WP_2 in row 1 are [0,0] and fit within WP1 and WP2 in row1 [0,145] --> therefor WC in table 1 for that row is equal to WC in table2
WP_1 and WP_2 in row 2 are [0,5] and fit within WP1 and WP2 in row1 [0,145] --> therefor WC in table 1 for that row is equal to WC in table2 ....
WP_1 and WP_2 in row 4 are [115,219] and DON'T fit within any pair of WP1 and WP2 in any row --> therefor WC in table 1 for that row is 2
WP_1 and WP_2 in row 5 are [219,262] and fit within WP1 and WP2 in row3 [169,1693] --> therefor WC in table 1 for that row is equal to WC in table2
My Code so far:
for n = 1:height(table1)
for m = 1:height(table2)
if table1.WP_1(n) >= table2.WP1(m) &...
table1.WP_2(n) <= table2.WP2(m)
table1.WC(n) = table2.WC(m);
else table1.WC(n) = 2;
end
end
end
Here is a simple brute force approach that uses find
to get the index of the first match where the value in the rows are within the ranges of the second table. If table2.WP2(n) == table2.WP1(n+1) always, there are some shortcuts that can be used.
% Preallocate the output as not found
table1.WC = ones(length(table1.WP_1),1) * 2;
for i = 1:length(table1.WP_1)
idx = find(and(table1.WP_1(i) >= table2.WP1, table1.WP_2(i) <= table2.WP2), 1, 'first');
if ~isempty(idx)
table1.WC(i) = table2.WC(idx);
end
end
You can replace the and(...,...)
with &
to make it shorter as well. I like the readability of and
.