[英]Storing and accessing matrix operated inside a function parallelized by pararrayfun of Octave/Matlab
Pararrayfun is used this way Pararrayfun使用这种方式
pkg load parallel;
# fun is the function to apply
fun = @(x) x^2;
vector_x = 1:10000;
vector_y = pararrayfun(16, fun, vector_x);
I intend to apply it to a function with this form 我打算将其应用于具有这种形式的功能
fun = @(i) zz(1:100,i+1) = z.^2;
where z is a column vector, and zz is a 100xi matrix. 其中z是列向量,zz是100xi矩阵。 I want to get the matrix zz out after the pararrayfun() but I get nothing back. 我想在pararrayfun()之后得到矩阵zz,但什么也没回来。 I dont know if I am using the right code or the right argument as I have just started using octave a month ago. 我不知道我是在使用正确的代码还是正确的参数,因为我一个月前才开始使用八度。 Any help would really be appreciated. 任何帮助将不胜感激。
Here is my attempted "full" code: 这是我尝试的“完整”代码:
pkg load parallel;
z = linspace(-1,10,100).';
fun = @(i) zz(1:100,i+1) = z.^2;
i = 0:9999;
pararrayfun(16, fun, i);
I tried to use global zz but I still get nothing. 我尝试使用global zz,但仍然一无所获。
The first answer is that the zz
variable inside you fun
is a local variable. 第一个答案是, fun
内部的zz
变量是局部变量。 It would have to be declared as global
, but this is not possible inside an anonymous function (defined with @() ...
). 必须将其声明为global
,但这在匿名函数 (用@() ...
定义@() ...
是不可能的。
One might be tempted to try to define fun
with 可能会想尝试定义fun
pkg load parallel;
z = linspace(-1,10,100).';
global zz
zz = zeros(100, 10000);
function fun1(idx, z)
global zz
zz(:, idx) = z.^2;
endfunction
fun = @(idx) fun1(idx, z)
idx = 1:10000;
pararrayfun(nproc, fun, idx);
But the zz
is not modified. 但是zz
没有被修改。 Probably because each thread has its own context. 可能是因为每个线程都有自己的上下文。
This is a good thing, because otherwise modifying a global variable inside a pararrayfun
call would lead to potential race conditions. 这是一件好事,因为否则在pararrayfun
调用中修改全局变量将导致潜在的竞争状况。
Here is a safer way: 这是一种更安全的方法:
pkg load parallel;
z = linspace(-1,10,100).';
fun = @(i) z.^2;
idx = 1:10000;
zz = pararrayfun(nproc, fun, idx);
As a side note, for this example, 附带说明一下,在此示例中,
zz = repmat(z, 1, 10000);
would be much faster. 会更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.