MATLAB利用parfor計算多重for迴圈
阿新 • • 發佈:2018-12-20
當MATLAB程式中出現多個for迴圈時,為提高執行效率,可用如下方式實現迴圈變數索引。
clear; clc;
M = 2;
N = 3;
R = 4;
parfor i = 1 : M * N * R
ii = floor((i - 1) / (N * R)) + 1;
jj = floor(mod(i - 1, N * R) / R) + 1;
kk = mod(i - 1, R) + 1;
fprintf('i = %d j = %d k = %d\n', ii, jj, kk);
end
執行結果
i = 1 j = 3 k = 4 i = 1 j = 3 k = 3 i = 1 j = 3 k = 2 i = 1 j = 3 k = 1 i = 1 j = 2 k = 4 i = 1 j = 2 k = 3 i = 1 j = 2 k = 2 i = 1 j = 2 k = 1 i = 1 j = 1 k = 4 i = 1 j = 1 k = 3 i = 1 j = 1 k = 2 i = 1 j = 1 k = 1 i = 2 j = 1 k = 4 i = 2 j = 1 k = 3 i = 2 j = 1 k = 2 i = 2 j = 1 k = 1 i = 2 j = 3 k = 1 i = 2 j = 2 k = 4 i = 2 j = 2 k = 3 i = 2 j = 2 k = 2 i = 2 j = 2 k = 1 i = 2 j = 3 k = 2 i = 2 j = 3 k = 3 i = 2 j = 3 k = 4