I made simple code to test for saving struct variable in parfor loop.
parfor k=1:3
my_field = sprintf('v%d', k);
variable.(my_field) = k*2;
end
But, i did not get the results I wanted, and there was only a variable with an empty value in the workspace.
If I use for instead of parfor, I get the result I want perfectly. However, the function(not the simple like above code) actually used takes a long time, so I want to use parfor.
How do I save a struct variable such as variable.v1, variable.v2 in a struct variable using parfor?

댓글 수: 3

KSSV
KSSV 2019년 2월 1일
YOu should first try to vectorise and see the possibilites of avoiding loop..won't you think you can achieve your code without loop?
Stephen23
Stephen23 2019년 2월 1일
편집: Stephen23 2019년 2월 1일
"If I use for instead of parfor, I get the result I want perfectly. "
I very much doubt that. Lets try it:
variable=struct();
for k=1:3
my_field = sprintf('v%d', k);
variable=struct(); % why do you overwrite this on every iteration?
variable.(my_field) = k*2;
end
On every loop iteration you completely overwrite variable, discarding anything that was stored in the variable on other loop iterations. Is that really what you mean by "I get the results I want perfectly" ?:
>> fieldnames(variable)
ans =
'v3'
"However, the function(not the simple like above code) actually used takes a long time, so I want to use parfor."
I very much doubt that parfor is a magic silver bullet for your runtime. Have you profiled your code to identify which lines take the most time? Have you followed the guidelines for writing efficient MATLAB code?:
Do you understand the overhead involved in running parallel code?
seung ho yeom
seung ho yeom 2019년 2월 1일
oops, sorry i change the code.

댓글을 달려면 로그인하십시오.

 채택된 답변

Stephen23
Stephen23 2019년 2월 1일
편집: Stephen23 2019년 2월 1일

0 개 추천

I doubt that parfor wil work happily with dynamic fieldnames, because their order of definition is ambiguous (e.g .consider naming them using the mod of your loop counter: parfor cannot predict in which order the fields should be overwritten, which for a normal for loop is unambiguous).
The best solution is to avoid the awkward, ambiguous, anti-pattern dynamic fieldnames, and just use simpler indexing with a non-scalar structure:
N = 3;
S = struct('val',cell(1,N));
parfor k = 1:N
S(k).val = k*2;
end
Unlike your "perfect" code, this really does keep all of the data that you calculate:
>> S.val
ans =
2
ans =
4
ans =
6

댓글 수: 1

seung ho yeom
seung ho yeom 2019년 2월 3일
Now, i use a non scalar strucure as you taught me, it works great! thank you!
Next, i think it is necessary to devise a method of making using vectorization method.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2019년 2월 1일

댓글:

2019년 2월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by