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 次查看(过去 30 天)
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))

采纳的回答

Thorsten
Thorsten 2014-11-17
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)'])

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by