Re: [問題]if迴圈問題

看板MATLAB作者 (sppmg)時間6年前 (2018/07/03 01:49), 編輯推噓1(102)
留言3則, 2人參與, 6年前最新討論串2/2 (看更多)
沒仔細想修正方法。直接給你「比較快」的作法。 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
說一下,for n ... 只是為了計時而重複算10次
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
文章代碼(AID): #1REcMYwT (MATLAB)
討論串 (同標題文章)
文章代碼(AID): #1REcMYwT (MATLAB)