To pass a variable outside a parfor loop

28 次查看(过去 30 天)
I have a loop that looks like:
parfor j=1:length(P)
for i=1:(length(A)-1)
%unnecessary calculations
for i=1:(length(A)-1)
end
for k=1:(length(B)-1)
ri(k,l)=len(k); %len is a vector, that has been defined already
sr(1,i)=r(i); %r is a vector, that has been defined already
end
%unnecessary calculations
end
%unnecessary calculations
end
plot(ri,sr); %I know that these two vectors have different dimensions, it's just example to show, that I use variables outside parfor
%loop. By the way, I use the variables in functions "plot" and "meshgrid"
So I tryed to use cell arrays as Walter Roberson recommend:
%in my program (length(A)-1)=40, (length(B)-1) = 10;
ri=cell(10,40); sr=cell(1,40);
parfor j=1:length(P)
for i=1:(length(A)-1)
for k=1:(length(B)-1)
ri{k,l}=len(k);
sr{1,i}=r(i);
end
end
end
ri1=cell2mat(ri);
sr1=cell2mat(sr); %last two lines are my own ideas I don't know good or bad
plot(ri1,sr1);
And matlab writes that because of the way of using variables the parfor loop can't be executed. It writes the same as before changing the code.
The main error is "Unable to classify the variable 'ri' in the body of the parfor-loop". Can you help me, please?

采纳的回答

George Bashkatov
George Bashkatov 2021-5-6
编辑:George Bashkatov 2021-5-6
1) replace (length(A)-1), length(P) and (length(B)-1).
2)make temporary variables lentemp and rtemp
3)add one more index j
4)choose data for plotting
r1=(length(A)-1); r2=length(P); r3=(length(B)-1); %replacing
parfor j=1:r2
for i=1:r1
rtemp=r; %making temporary variables
for k=1:r3
lentemp=len; %making temporary variables
ri(k,l,j)=lentemp(k); %adding index
sr(1,i,j)=rtemp(i); %adding index
end
end
end
plot(ri(:,:,end),sr(:,:,end)); %choosing data

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by