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

1 次查看(过去 30 天)
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)

回答(1 个)

per isakson
per isakson 2019-10-18
编辑:per isakson 2019-10-18
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 个评论
SammyJoe
SammyJoe 2019-10-18
This gives this error:
Undefined function or variable 'nans'.
Error in configurebeads1 (line 23)
c = nans(n,1);
per isakson
per isakson 2019-10-18
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by