How can i operate on every newly created vector in a for loop?
2 次查看(过去 30 天)
显示 更早的评论
I am trying to build all possible permutations of a vector following this rule: Subsequene entries in the vector can either decrease by exactly 1 or increase by any amount. I start with the vector [1] and then modify it and append 2 to create [1 2] and [2 1]. Notice that each new vector should also probude 2 subsequent vectors, one with the new value of n appended on the very end, and one with the new value of n appended right before (n-1). I cannot seem to get MatLab to operate on every single newly created vector while in the foor loop (since more and more vectors are created every iteration).
clear
n=input('Input value for n\n'); %Set n-value.
P=[]; %Define an empty permutation matrix.
P(1,:)=[1]; % Valid Permutation for n=1
M{1} = P; % Putting that permutation in a call array.
for i=2:n
v1=[M{i-1} i]; %This creates all the [1 2 3 ... n] perms
v2=[M{i-1}(1:find(M{i-1}==(i-1)-1)) i M{i-1}(find(M{i-1}==(i-1)):end)]; % This creates all [1 2 ... (n-1) n] permutations.
% It doesnt look like my script operates on EVERY newly created vector to create ALL valid permutations.
M{i}=v1;
N{i}=v2;
end
G=[M; N]
for i=1:n
G{i}
end
How can I get my script to apply the two operations in the for loop to EVERY newly created vector during the previous iteration?
2 个评论
回答(1 个)
Bob Thompson
2019-2-1
Ok, I think maybe all you need to do is add a second internal loop to loop through all the cells of the previous iteration.
for i = 2:n;
for j = 1:length(M{i-1})
v1 = [M{i-1}{j} i];
v2 = [M{i-1}{j}(...% Other stuff)];
M{i}{j} = v1;
N{i}{j} = v2;
end
end
I tried to keep this as similar to what you already had, but basically you should have a cell array M which contains a cell for each iteration. Then each of those cells will contain an array of the different arrays.
2 个评论
Bob Thompson
2019-2-1
No, not if your variable got defined with the internal cells. I would suggest returning to the first error and determining the class of i and M{i-1}{j}. It's possible that they are not the same class, and the code is trying to concat a cell and a double or something.
You also need to make sure you are initializing your M{1} to a second level of cells (M{1}{1}) in order for M{i-1}{j} to work the first time through.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!