Need to test all permutations

1 次查看(过去 30 天)
Say I have the following:
A = [1 2 3], B = [1 2], C = [4],
D = C + B*A
I need D to contain all permutations of C+B*A:
D1 = 4+1*1
D2 = 4+1*2
D3 = 4+1*3
D4 = 4+2*1
D5 = 4+2*2
D6 = 4+2*3
What is this called and what tools are available to perform this on bigger equations?

采纳的回答

Star Strider
Star Strider 2019-4-6
One approach is to use the ndgrid (link) function:
A = [1 2 3];
B = [1 2];
C = [4];
[p1,p2,p3] = ndgrid(A,B,C);
P = [p3(:),p2(:),p1(:)]; % Components
D = p3(:) + p2(:).*p1(:)
The ‘P’ assignment simply displays the components used in the ‘D’ calculation. It is not otherwise necessary for the code.
I cannot guarantee that this will easily scale to other problems. It works here.
  6 个评论
Star Strider
Star Strider 2019-4-6
编辑:Star Strider 2019-4-6
Craig Dekker’s Answer moved to this Comment:
Thank you.
I'll try breaking the equation into several nested loops.
Star Strider
Star Strider 2019-4-6
As always, my pleasure.
That may not be absolutely necessary.
I simply don’t understand your notation well enough to figure out how to use the ndgrid approach with it.
Experiment with something like this:
Dv1 = [1 2];
M2v1 = [3 4 5];
M1v1 = [6 7 8 9 10 11];
Fmv1 = (12:12+17);
Rv1 = [30 31];
[p1,p2,p3,p4,p5] = ndgrid(Dv1,M2v1,M1v1,Fmv1,Rv1);
Rv = p5(:);
Fmv = p4(:);
M1v = p3(:);
M2v = p2(:);
Dv = p1(:);
It seems that it might work, although I can’t guarantee it. I may also have missed something, since this code produces a series of (1296x1) vectors, while:
veclen = 2*3*6*3*18*2*2;
would have 7776 elements.
If the ndgrid approach works, it would definitely be faster than nested for loops. The challenge then comes in reshaping the output vector into a matrix that is meaningful in terms of the argument vectors. Appropriately indexing the result is the principal reason I would err on the side of the loops.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Just for fun 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by