我有,我用它來計算收斂一些的在Collatz序列所需的迭代一個代碼:如何在嵌套的WHILE循環中附加一個矩陣是MATLAB中的一個PARFOR循環?
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
不久,它計算到num
將在Collatz序列將數字加起來,在最大記錄數序列,並記錄減少的次數爲1的迭代次數。
與seqn
矩陣,我試圖記錄我運行循環的每個數字的Collatz sequnece。
這裏的問題是MATLAB不會運行這個PARFOR
循環,因爲對seqn
進行了更改。我不明白原因!在我看來,我對iter
所做的與seqn
基本上是一樣的,因爲它在嵌套的WHILE
循環內執行,並且不依賴於以前的迭代。
我能做些什麼來解決這個問題?
[這個答案由MATLAB員工(http://stackoverflow.com/a/37696213/5211833 )可能會幫助你,它看起來像你想要的一樣。一般'parfor'提示可以在[我的答案]中找到(http://stackoverflow.com/questions/32146555/saving-time-and-memory-using-parfor-in-matlab/32146700#32146700)。 (我現在會刪除其他評論,因爲我認爲他們中的一半或者錯誤,或者被這裏的答案覆蓋,並且清理一下) – Adriaan