Generalizing algorithm to find all combinations of sums of vectors.
古いコメントを表示
Hello all. I need some help with generalizing an algorithm I wrote. Here is my code:
% Define vectorfield
g1=[5,0,0];
g2=[0,3,0];
g3=[0,0,4];
% Define on-off
u=[0;1];
% Define set to make field symmetric
symm=[1;-1];
k=1;
% Generate possible combinations of vector fields
for a=1:length(u)
for b=1:length(symm)
for c=1:length(u)
for d=1:length(symm)
for e=1:length(u)
for f=1:length(symm)
allvecfields(k,:)=u(a).*symm(b).*g1+u(c).*symm(d).*g2+u(e).*symm(f).*g3;
k=k+1;
end
end
end
end
end
end
realfields=transpose(unique(allvecfields,'rows'));
Each column of realfields is a unique positive, negative or zero combination of the g's. I need some help generalizing this. That is the size of each g can be n, and the number of g's can be m. The code should still return all the unique possible combinations of the g's. I have a feeling that recursion will have to be used but all my attempts have failed so far.
I have looked at combvec and the allcomb file but they don't do what I need. For example
transpose(unique(combvec(g1,g2,g3,-g1,-g2,-g3)','rows'))
returns a 6x63 matrix not the 3x27 that I want.
I have been able to rewrite the above as
u=[-1,0,1];
k=1;
for a=1:length(u)
for b=1:length(u)
for c=1:length(u)
uMat(k,:)=[u(a) u(b) u(c)];
k=k+1;
end
end
end
g1=[5,0,0];
g2=[0,3,0];
g3=[0,0,4];
gMat=[g1' g2' g3'];
for a=1:size(uMat,1)
allvecfields(k,:)=sum(bsxfun(@times,gMat,uMat(a,:)),2);
end
realfields=transpose(unique(allvecfields,'rows'))
which I think this is slightly more elegant but I am still stuck at how to dynamically generate uMat given the number of columns in gMat. Any help would be appreciated.
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Univariate Discrete Distributions についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!