Generalizing algorithm to find all combinations of sums of vectors.
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Ivan Abraham
le 14 Juin 2016
Commenté : Ivan Abraham
le 15 Juin 2016
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 commentaires
Réponse acceptée
Roger Stafford
le 15 Juin 2016
Let’s suppose that the g’s are the rows in an m by n matrix, G. That is, each n-element row is one of the g’s and there are m of them.
T = zeros(3^m,m);
for k = 1:3^m
T(k,:) = double(dec2base(k-1,3,m)-‘1’); % The T values will be -1, 0, or 1
end
A = T*G;
Then A will be your desired ‘allvecfields’ array.
Note: In your first code there is duplication of the possible values of u*symm. Its four combinations yield the values 0,0,1,-1 with only three different values. The code above does not have these duplications and A has only 3^m rows rather than 4^m.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Introduction to Installation and Licensing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!