0
votes

I have a problem with MathWorks Parallel Computing Toolbox in Matlab. See my code below

for k=1:length(Xab)
    n1=length(Z)*(k-1)+1:length(Z)*k;
    MX_j(1,n1)=JXab{k};
    MY_j(1,n1)=JYab{k};
    MZ_j(1,n1)=Z;
end
for k=length(Xab)+1:length(Xab)+length(Xbc)
    n2=length(Z)*(k-1)+1:length(Z)*k;
    MX_j(1,n2)=JXbc{k-length(Xab)};
    MY_j(1,n2)=JYbc{k-length(Yab)};
    MZ_j(1,n2)=Z;
end

for k=length(Xab)+length(Xbc)+1:length(Xab)+length(Xbc)+length(Xcd)
    n3=length(Z)*(k-1)+1:length(Z)*k;
    MX_j(1,n3)=JXcd{k-length(Xab)-length(Xbc)};
    MY_j(1,n3)=JYcd{k-length(Yab)-length(Ybc)};
    MZ_j(1,n3)=Z;
end

for k=length(Xab)+length(Xbc)+length(Xcd)+1:length(Xab)+length(Xbc)+length(Xcd)+length(Xda)

    n4=length(Z)*(k-1)+1:length(Z)*k;
    MX_j(1,n4)=JXda{k-length(Xab)-length(Xbc)-length(Xcd)};
    MY_j(1,n4)=JYda{k-length(Yab)-length(Ybc)-length(Ycd)};
    MZ_j(1,n4)=Z;
end

If I change the for-loop to parfor-loop, matlab warns me that MX_j is not an efficient variable. I have no idea how to solve this and how to make these for loops compute in parallel?

1
parfor is NOT a magic wand. Are you sure you have optimised the loops as far as possible? - Adriaan

1 Answers

0
votes

For me, it looks like you can combine it to one loop. Create combined cell arrays.

JX = cat(2,JXab, JXbc, JXcd, JXda);
JY = cat(2,JYab, JYbc, JYcd, JYda);

Check for the right dimension here. If your JXcc arrays are column arrays, use cat(1,....

After doing that, one single loop should do it:

n = length(Xab)+length(Xbc)+length(Xcd)+length(Xda);
for k=1:n
    k2 = length(Z)*(k-1)+1:length(Z)*k;
    MX_j(1,k2)=JX{k};
    MY_j(1,k2)=JY{k};
    MZ_j(1,k2)=Z;
end

Before parallizing anything, check if this still valid. I haven't tested it. If everything's nice, you can switch to parfor.

When using parfor, the arrays must be preallocated. The following code could work (untested due to lack of test-data):

n = length(Xab)+length(Xbc)+length(Xcd)+length(Xda);
MX_j = zeros(1,n*length(Z));
MY_j = MX_j;
MZ_j = MX_j;
parfor k=1:n
    k2 = length(Z)*(k-1)+1:length(Z)*k;
    MX_j(1,k2)=JX{k};
    MY_j(1,k2)=JY{k};
    MZ_j(1,k2)=Z;
end

Note: As far as I can see, the parfor loop will be much slower here. You simply assign some values... no calculation at all. The setup of the worker pool will take 99.9% of the total execution time.