Re: [問題]if迴圈問題
沒仔細想修正方法。直接給你「比較快」的作法。
matlab 要快要向量化寫法,我在 octave + 弱筆電執行我的程式後的輸出為:
answer same, for = 1.06e+01 s, vec = 1.71e-02 s
Vectorization 619.79 x faster then for loop.
Original outer number is 10000, after mod() is 0
這程式假設你ao,bo,co 都是常數、不隨位置改變。
以下程式
(註:其中的 clear -x ... 在 matlab 要改用 clearvars -except ...)
-------
clear all ;
ao = 0 ; bo = 200 ; co = 1000 ;
t0_for = tic;
for n = 1:10
as = linspace(-3.3,3.3,100);
bs = linspace(-3.3,3.3,100);
cs = 0;
ts = zeros(100,100);
for i = 1:100
for j = 1:100
ts(i,j) = 0.1238 - sqrt((ao-as(i))^2 + (bo-bs(j))^2 + (co-cs)^2)/1500;
end
end
end
t_for = toc(t0_for) ;
% ------
clear -x t_for ts ao bo co;
t0_vec = tic ;
for n = 1:10
as = linspace(-3.3,3.3,100);
bs = linspace(-3.3,3.3,100);
cs = 0;
tts = 0.1238 - sqrt( ((ao - as)'.^2)*ones(1,100) + ones(1,100)'*((bo-bs).^2) + (co-cs).^2) ./1500;
end
t_vec = toc(t0_vec) ;
if isequal(tts,ts)
fprintf('answer same, for = %0.2e s, vec = %0.2e s \nVectorization %0.2f x faster then for loop.\n', t_for, t_vec, t_for/t_vec);
end
% ======
count_outer_orig = sum(sum(tts > 0.495 | tts < 0)) ;
mtts = mod(tts, 0.495) ;
count_outer_mod = sum(sum(mtts > 0.495 | mtts < 0)) ;
fprintf('Original outer number is %d, after mod() is %d\n', count_outer_orig, count_outer_mod) ;
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.97.51.122
※ 文章網址: https://www.ptt.cc/bbs/MATLAB/M.1530553762.A.E9D.html
→
07/03 01:50,
6年前
, 1F
07/03 01:50, 1F
推
07/03 20:30,
6年前
, 2F
07/03 20:30, 2F
→
07/03 20:30,
6年前
, 3F
07/03 20:30, 3F
討論串 (同標題文章)
MATLAB 近期熱門文章
PTT數位生活區 即時熱門文章