フィルターのクリア

Why doesn't MATLAB support 'cpuArray' for some array creation functions?

1 回表示 (過去 30 日間)
Meng-Yuan Huang
Meng-Yuan Huang 2018 年 1 月 17 日
編集済み: Meng-Yuan Huang 2018 年 1 月 17 日
For example, we can create a GPU array by code:
rand(3, 'single', 'gpuArray')
Unfortunately, this code will fail if it is run on a PC without a CUDA graphics card. If we can pass 'cpuArray' to rand, we can easily write a MATLAB program for both CPU and GPU computings. E.g.,
useGpu = 0
if(useGpu)
arrayType = 'gpuArray';
else
arrayType = 'cpuArray';
end
% The program ...
A = rand(3, 'single', arrayType);
B = rand(3, 'single', arrayType);
C = A*B;
(Unfortunately, this example doesn't work for current MATLAB...)
Otherwise, we have to write this code:
useGpu = 0
if(useGpu)
A = rand(3, 'single', 'gpuArray');
B = rand(3, 'single', 'gpuArray');
else
A = rand(3, 'single');
B = rand(3, 'single');
end
C = A*B;
Could MathWorks add 'cpuArray' to most array creation functions in the future?

採用された回答

Edric Ellis
Edric Ellis 2018 年 1 月 17 日
Another workaround is to use a cell array.
if useGpu
arg = {'gpuArray'};
else
arg = {};
end
A = rand(3, 'single', arg{:});
The {:} syntax converts arg into a comma-separated list.
  1 件のコメント
Meng-Yuan Huang
Meng-Yuan Huang 2018 年 1 月 17 日
編集済み: Meng-Yuan Huang 2018 年 1 月 17 日
Thanks. Your workaround is better, because we can specify data type for each array.

サインインしてコメントする。

その他の回答 (1 件)

Meng-Yuan Huang
Meng-Yuan Huang 2018 年 1 月 17 日
I find a workaround:
useGpu = 1;
if(useGpu)
arg1 = 'single';
arg2 = 'gpuArray';
else
arg1 = 1;
arg2 = 'single';
end
% The program ...
A = rand(3, 3, arg1, arg2);
B = rand(3, 3, arg1, arg2);
C = A*B

カテゴリ

Help Center および File ExchangeGPU Computing についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by