Is it possible to change two functions using parforma?

Suppose I have two functions written in different scripts, say function1.mand function2.m. Two calculations in two functions are independent (some inputs may be the same, for example, function1(x,y)and function2(x,z)). However, working sequentially, say, ret1 = function1(x,y); ret2 = function2(x,z);can be time consuming. I wonder if it can be run in a loop parfor:

parfor i = 1:2
ret(i) = run(['function' num2str(i)]); % if i=1,ret(1)=function1 and i=2, ret(2)=function2
end

Is it possible to write it in a loop parfor?

+4
source share
3 answers

Your idea is correct, but the implementation is wrong.

Matlab run parfor, , parfor (.. ). - ( ) if :

ret = zeros(2,1);
parfor k = 1:2
    if k==1, ret(k) = f1(x,y);  end
    if k==2, ret(k) = f2(x,z);  end
end

f1 f2 - , ( ret(k), if.

.

+3

parfor , . ,

- . , .

, .

, , , ,

parfor (i = 1:2)
    function1(iterator,someNumber); 
    function2(iterator,someNumber);
end

parfor.

, , , ,

persistentValue = 0;
parfor (i = 1:2)
    persistentValue = persistentValue + function1(iterator,someNumber); 
    function2(iterator,persistentValue);
end

.

+1

. .

:

ret = zeros(2,1);
fHandles = {@min, @max};
x = 1:10;        
parfor i=1:2
    ret(i) = fHandles{i}(x);    
end
ret   % show the results.

, . , .

  • , , parfor, . , 2 , , .
  • (, i, , ), t .

, MATLAB .

ret = zeros(2,1);
fHandles = {@min, @max};
x = 1:10;         % x is a 1x10 vector
y = rand(20);     % y is a 20x20 matrix
z = 1;            % z is a scalar value
fArgs = {{x};
         {y,z}};  %wrap your arguments up in a cell
parfor i=1:2
    ret(i) = fHandles{i}([fArgs{i}{:}]);  %calls the function with its variable sized arguments here
end
ret   % show the output

, . MATLAB fArgs .

0

Source: https://habr.com/ru/post/1682812/


All Articles