Save each pair in container.Map to separate variable in .mat file

Hi I Have a container.Map object in which I need each key, value pair to be saved to a variable within a mat file.
Was originaly doing this with eval but then discovered assignin. Is there a better way to do this?
I need the outputted mat file to contain individual variables and so can't just use list due to the application this .mat file will be used in.
Simplified code snippet below
M = container.Map();
M("var1") = [1 2 3];
M("var2") = [4 5 6];
saveVars = {};
for key = M.keys()
assignin('base', key, M(key))
saveVars(end+1) = key
end
save("output.mat", saveVars{:})

댓글 수: 2

Stephen23
Stephen23 2021년 2월 1일
편집: Stephen23 2021년 2월 1일
"Was originaly doing this with eval but then discovered assignin."
Replacing eval with assignin does not avoid any of the problems of dynamic variable names, in fact you just add extra obfuscation and latent bugs to the process (i.e. as well as having all of the disadvantages of using eval).
OK thanks. I'm aware of the problems but due to the specific use case there was nothing I could do to avoid this. Thanks for your solution worked excatly like i wanted. The names come from a seperate file and must be as specified.

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

 채택된 답변

Stephen23
Stephen23 2021년 2월 1일
편집: Stephen23 2021년 2월 1일
"Is there a better way to do this?"
Of course, just use the -struct option when calling save. Note that conversion to structure relies on the keys being valid fieldnames, which we already know they must be because you are anyway using them as variable names.
M = containers.Map();
M("var1") = [1,2,3];
M("var2") = [4,5,6];
% convert to struct:
C = [keys(M);values(M)];
S = struct(C{:});
save('myfile.mat','-struct','S')

추가 답변 (0개)

카테고리

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

제품

릴리스

R2017b

질문:

2021년 2월 1일

댓글:

2021년 2월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by