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

1 回表示 (過去 30 日間)
SammyJoe
SammyJoe 2019 年 10 月 18 日
コメント済み: per isakson 2019 年 10 月 18 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by