Flexible property class validation; allow property to be one of several classes (or be a gpuArray)?

4 ビュー (過去 30 日間)
D. Plotnick
D. Plotnick 2019 年 4 月 29 日
編集済み: per isakson 2019 年 5 月 5 日
Hello all, this is an example of what I am trying to do:
classdef myClass
properties
val (:,1) single = 0; % Some column vector of single precision data
end
methods
function obj = myClass(val)
if nargin >= 1
obj.val = val;
end
end
end
end
Now, I always want the data in myClass.val to be at single precision, but I may want to load it onto the GPU temporarily for computations. If I do this outside of my object, I can use:
a = rand(10,1);
a = single(a);
a = gpuArray(a)
class(a)
The latter two commands return:
a =
10×1 single gpuArray column vector
0.9340
0.6787
0.7577
0.7431
0.3922
0.6555
0.1712
0.7060
0.0318
0.2769
and
ans =
'gpuArray'
respectively. Now, Matlab clearly knows that a is a single gpuArray, but I don't know how to return that precision as part of the class short of something like c = class(gather(a(1))), which is just silly.
The bigger problem is that if I do:
mc = myClass(a)
Error using myClass (line 8)
Error setting property 'val' of class 'myClass':
Invalid data type. Value must be single or be convertible to single.
Since the gpuArray class fails the validation step. I want write this in such a way that the data is of single precision, but can be on or off of the GPU. Something like:
classdef myClass
properties
val (:,1) {single,gpuSingle} = 0; % Some column vector of single precision data
end
end
which runs into two issues: I cannot define multple types in validation, and I do not know what the actual correct class name is for a single precision GPU array (since class(a) returns 'gpuArray' regardless of the precision of a.
Would it be better to shift the burden out of the property block, and into a set method? E.g.
methods
function obj = set.val(obj,val)
obj.val = single(val);
end
end
which in at least this case is fine, since 'single' is also a method of gpuArray. However, I may also want something more like
properties
val (:,1) {single,cell} = 0; % Some column vector of single precision data
end
where I change behavior of methods based on whether obj.val is a numerical array or a cell array. A pair of basic methods for motivation:
function obj = doThing(obj)
obj.val = arrayfun(@(x) myFun(obj,x),1:10,'UniformOutput',false);
end
function out = view(obj)
if iscell(obj.val)
out = cat(2,obj.val{:})
else
out = obj.val;
end
imagesc(out)
end
TLDR - Is there any way of using property class validation that enforces precision, but allows for gpuArrays, or to allow for the property's class to be a member of a set of classes?
How do I get the precision of a gpuArray?
Any other suggestions?
Cheers,
-DP

回答 (0 件)

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by