I have a code that I use to compute the iterations needed to converge a number's Collatz sequence to one:
nums = input('Enter a number: ');
iter = zeros(1, nums, 'uint16');
collatz = zeros(1, nums, 'uint64');
seqn = zeros(nums, 'uint64');
parfor ii = 1:nums
num = ii;
collatz(ii) = num;
% seqn(ii) = num;
while num ~= 1
% writes the maximum number reached
if collatz(ii) < num
collatz(ii) = num;
end
if rem(num, 2) == 0
num = num / 2;
else
num = 3 * num + 1;
end
% counts iterations needed to reduce each number to one
iter(ii) = iter(ii) + 1;
% records the sequence
seqn(:, iter(ii)) = num;
end
end
Shortly, it computes the Collatz sequence for each number up to num
, records the maximum number in the sequence, and records the number of iterations ot took to reduce the number to one.
With the seqn
matrix, I'm trying to record the Collatz sequnece of each number I run the loop for.
The problem here is that MATLAB won't run this PARFOR
loop because of the changes done to seqn
. I don't understand the reason! It seems to me that what I do to iter
is essentially the same thing I do to seqn
, in the sense that it executes inside the nested WHILE
loop and does not depend on previous iterations.
What can I do to fix this?