How do I save each iteration of a loop into a matrix?

1 view (last 30 days)
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)

Answers (1)

per isakson
per isakson on 18 Oct 2019
Edited: per isakson on 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 Comments
SammyJoe
SammyJoe on 18 Oct 2019
This gives this error:
Undefined function or variable 'nans'.
Error in configurebeads1 (line 23)
c = nans(n,1);
per isakson
per isakson on 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

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!