필터 지우기
필터 지우기

Saving variables within a parfor loop

조회 수: 16 (최근 30일)
Sean Pierre
Sean Pierre 2015년 9월 6일
댓글: Walter Roberson 2015년 9월 6일
I wish to save individual variables in my script that are defined in a parfor loop. I defined a function called saveVariables.m that would save a specified variable to a .mat file as follows.
function l = saveVariables(local_filename, variable, index)
save(['simulation_' num2str(index) '\' local_filename], variable)
l = 1;
end
The issue that I have is that MATLAB produces the error
Error using saveVariables (line 4)
Argument must contain a string.
I use the backlash '\' since I am running Matlab on Windows. local_filename is meant to be the string of the name of the file that I wish to save. How can I work around this string error?

채택된 답변

Mohammad Abouali
Mohammad Abouali 2015년 9월 6일
Two things:
(1) When using save() the way that you are using the second input must be also an string. So if you want to save a variable called myVariable in a file called myOutputFile='D:\myDataFolder\somename.mat' then you have to issue the command as follows:
save(myOutputFile,'myVariable')
Note the quote around myVariable.
This is different when you use the non-function form of the save() as follow:
save 'D:\myDataFolder\somename.mat' myVariable
(2) save() command does not work in SPMD or PARFOR section. Click here for another post about the same topic;
You need to first define a function as follows:
function savetofile(data,fullfilename)
save(fullfilename,'data');
end
and then whenever you are in SPMD and PARFOR and willing to save something instead of using the regular save() command use the above function as follows:
savetofile(myVariable,myOutputFile)

추가 답변 (1개)

Walter Roberson
Walter Roberson 2015년 9월 6일
But what are you passing in for "variable" ? It must be the name of a variable.
You should consider using fullfile() . And you should consider using sprintf() to construct the name.
save( fullfile(sprintf('simulation_%d',index), local_filename), variable)
  댓글 수: 4
Sean Pierre
Sean Pierre 2015년 9월 6일
I am still receiving the same error of
Error using saveVariables (line 3)
Variable 'RD' not found.
. I changed my saveVariables script to
function l = saveVariables(local_filename, variable, index)
save( fullfile(sprintf('simulation_%d',index), local_filename), inputname(2));
l = 1;
end
and I call it with
saveVariables( 'RD_1pk.mat', RD, j);
Walter Roberson
Walter Roberson 2015년 9월 6일
function l = saveVariables(local_filename, variable, index)
varname = inputname(2);
savestruct.(varname) = variable;
save( fullfile(sprintf('simulation_%d',index), local_filename), '-struct', 'savestruct')
l = 1;
end

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

카테고리

Help CenterFile Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by