首先介紹幾個今天剛學的幾個函數:
1、linspace。產生指定范圍內的指定數量點數,相鄰數據跨度相同,並返回一個行向量。其在CPU和GPU中的調用形式
X=linspace(5,100,20) % 產生從5到100范圍內的20個數據,相鄰數據跨度相同 X=gpuArray.linspace(5,100,20) % 產生從5到100范圍內的20個數據,相鄰數據跨度相同
輸出:
X = 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 gX = 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
2、arrayfun。調用形式例:idx = arrayfun(@calcidx, Z0); % 對Z0中的每個元素調用calcidx函數,結果返回到idx中。(PS:避免無謂的循環)
s=[1 2;3 4]; s=gpuArray(s); % 在CPU中可以不要這句 f=@(x) x^2; arrayfun(f,s) ans = 1 4 9 16
注意:在編寫某個子函數時,特別是在GPU的運算中,可能會出現如下問題,雖然我暫時沒遇見過,也不知道為啥。
function output = calcidx(input) % calc index value for each element in Z0 z = complex(0,0); k = 0; % 這個 初始化k 不能省,否則出錯 for k = 0 : max_iter-1 z = z * z + input; if abs(z) > 2, break; end end output = k; end
3、關於GPU中的函數調用
與傳統matlab函數調用方法一樣,可以先將變量用gpuArray()函數搬到gpu中后再進行調用,或者在子函數中將變量搬遷到gpu中計算。當然本人推薦第一種。
具體調用對比如下:
[tmpRMSE_me] = RMSE_me(dataTrainPCA',labelTrain',dataTestPCA',labelTest',param); % CPU中 [tmpRMSE_me1] = RMSE_me(gpuArray(dataTrainPCA'),gpuArray(labelTrain'),gpuArray(dataTestPCA'),gpuArray(labelTest'),param); % GPU中
Note:GPU arrays support only fundamental numeric or logical data types.(GPU)
容易出現的錯誤如下:
An unexpected error occurred during CUDA execution. The CUDA error was: CUDA
解決方法:重啟Matlab 或 重啟電腦,因為GPU崩潰了。