How do I save each iteration of a loop into a matrix?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
per isakson
am 18 Okt. 2019
Bearbeitet: per isakson
am 18 Okt. 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 Kommentare
per isakson
am 18 Okt. 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
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!