Matlab GPU use with functions that take arguments of different dimensions

1 view (last 30 days)
I am trying to use parallel computing with GPU in Matlab, and I would like to apply a function to a large array (to avoid the use of a for loop, which is quite slow). I have read Matlab's documentation, and I can use arrayfun, but only if I want to do elementwise operations. Maybe I am confused, but I would appreciate if someone can help me to use it. As an example of what I want to do, imagine that I would like to perform the following operation,
X_t = B Z_t + Qe_t
where X_t is 2x1, B is 2x5, and Z_t is 5x1, with Q 2x2.
I define a function,
function X = propose(Z,B,Q)
X=Z*B+Q*rand(2,1);
end
Now, suppose that I have an array Z_p which is 5x1000. To each of the 1000 columns I would like to apply the previous function, for given matrices B and Q, to get an array X_p which is 2x1000.
Given the documentation for `arrayfun` I can not do this,
Xp=arrayfun(@propose,Zp,B,Q)
So, is there any possibility to do it?
Thanks!
*PS*: Yes, I know that in this simple example I can just do the multiplication without a for loop, but the application I have in mind is more complicated and I cannot do it. I just put this example as an illustration.

Answers (1)

Joss Knight
Joss Knight on 9 Sep 2015
Edited: Joss Knight on 9 Sep 2015
pagefun is what you're looking for. With it you can batch vector and matrix operations across pages of an array (the 3rd dimension). Obviously in your case simple vector algebra would do the trick but to force it to use pagefun you might do something like
N = size(Zp,2);
Zp = reshape(Zp, 5, 1, []); % Stack Z-vectors along the 3rd dimension
BZ = pagefun(@mtimes, B, Zp); % Assumes you wanted to multiply same B by every Z
offset = pagefun(@mtimes, Q, gpuArray.rand(2,1,N));
Xp = pagefun(@plus, BZ, offset); % Completely unnecessary, Xp = BZ+offset would work
  3 Comments
Carlos
Carlos on 10 Sep 2015
Well...it does not work. I mean, it works for this simple illustration that I posted here, but my problem requires a user defined function, with some more complex algebra, and pagefun does not admit them, while arrayfun does :(
Joss Knight
Joss Knight on 12 Oct 2015
pagefun can call any function that arrayfun can call, it just can't call lots of them in a single launch. Perhaps by breaking up your arrayfun function into multiple calls to pagefun, you can achieve what you're after.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!