How do I save each iteration of a loop into a matrix?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
This is my code; the problem is when I use a loop for circular shifts, I need each iteration to be saved into a matrix so I can concantenate it with two other matrices and take out duplicates
% This script will calculate the number of possible arrangements for a
% necklace given a certain number of beads assuming circular shifts and
% flips are the same
%Create a vector with the beads where a number is assigned to each color
v=[1 1 2 2 3 4];
% 1=red
% 2=blue
% 3=yellow
% 4=green
% Determine total number of beads and all possible permutations
n=numel(v);
p=perms(v);
% Take into account colors with >1 beads
p2=unique(perms(v),'rows');
% Generate flips of all permutations
f=fliplr(p2);
% Generate circular shifts for all permutations
for i=0:n
c=circshift(p, [0, i]);
end
% Combine the three matrices into one and remove duplicate rows
combined=[p2;f;c];
final=unique(combined,'rows');
configurations=size(final,1);
fprintf('The number of possible configurations is %d\n',configurations)
0 commentaires
Réponses (1)
per isakson
le 18 Oct 2019
Modifié(e) : per isakson
le 18 Oct 2019
Replace
for i=0:n
c=circshift(p, [0, i]);
end
by
c = nans(n,1);
for i=0:n
c(i)=circshift(p, [0, i]);
end
2 commentaires
per isakson
le 18 Oct 2019
My fault, the name of the function is nan
Then there is another problem. The Matlab arrays are one-based.
Thus
c = nan(n+1,1);
for i=0:n
c(i+1)=circshift(p, [0, i]);
end
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!