Two for loops, one loop completes for each step of another loop... Or a better way of doing finding the different combinations of elements in a vector that sum to target value
1 view (last 30 days)
Show older comments
I have two 2x100 matrices (M1 and M2) of the following form:
Variable1 100 200 300 400 500 600 700 800 900 1000
Output1 .60 .61 .62 .63 .64 .65 .66 .68 .67 .65
Variable2 100 200 300 400 500 600 700 800 900 1000
Output2 .66 .67 .68 .67 .67 .66 .67 .68 .65 .67
I want to create a new matrix containing the combinations of variable1 and variable2 where they fall within a specified range, say Target=1000 (+/-10). So it would look like this...
Variable1 100 200 300 400.....
Variable2 900 800 700 600.....
Sum of Outputs 1.25 1.29 1.29 1.29.....
I started with this:
TargetLocs=(M1(1,:)+M2(1,:)<(Target+10)) & (M1(1,:)+M2(1,:)>(Target-10))
However this only finds 1 example, where variable1=500 and variable2=500 because it loops through 1 column at a time. So I think I need to have two loops, like below, where I loop through j=1:length(M1) for every value of i=1:length(M1)... Struggling to code this, and part of me thinks there's probably a more efficient way of doing it?
TargetLocs=(M1(1,(i))+M2(1,(j))<(Target+10)) & (M1(1,(i))+M2(1,(j))>(Target-10))
0 Comments
Accepted Answer
Thorsten
on 17 Nov 2014
v1 = 100:100:1000; v2 = 100:100:1000;
[V1 V2] = meshgrid(v1, v2);
ind = find(abs(V1 + V2 - 1000) < 10);
o1 = [.60 .61 .62 .63 .64 .65 .66 .68 .67 .65];
o2 = [.66 .67 .68 .67 .67 .66 .67 .68 .65 .67];
[O1 O2] = meshgrid(o1, o2);
sumO = O1 + O2;
[i j] = ind2sub(size(V1), ind)
disp([v1(i); v2(j); sumO(ind)'])
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!