saving variables programmatically using list of variable names

조회 수: 91 (최근 30일)
checker
checker 2020년 6월 5일
댓글: checker 2020년 6월 5일
Hi all,
This should be simple but I think my frustration level is keeping me from seeing the path.
I simply want to save some variables on the workspace based on a list of those variable names.
a=1;b=2;c=3
varNames = {'a','b','c'};
save('myMatFile',varNames)
which yields the error 'Error using save. Must be a string scalar or character vector'. (what must be a string scalar? File name? vars? Yes I know, vars, but still TMW...)
so how about
save('myMatFile',cell2mat({'a,','b,','c'});
yielding the more useful error 'a,b,c' is not a valid variable name.
I see where this is going, I must have a properly formatted string array akin to eval inputs. But there really should be an easier way, like my original attempt.
Thanks for the support and letting me rant a bit.
-Chris
  댓글 수: 1
Steven Lord
Steven Lord 2020년 6월 5일
That message does seem vague. I've reported that to the development staff.

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

채택된 답변

Stephen23
Stephen23 2020년 6월 5일
편집: Stephen23 2020년 6월 5일
The simple solution is to use a comma-separated list:
varNames = {'a','b','c'};
save('myMatFile',varNames{:})
% ^^^ you need this!
Tip: when load-ing the file data you should use an output variable (which is a scalar structure):
S = load(...);
  댓글 수: 1
checker
checker 2020년 6월 5일
OK, I've accepted this as a correct answer since it does the job nicely and simply, thanks. intuitively or more importantly per the help for 'save'? Not so much. How is varNames{:} equivalent to a 'string scalar or character vector'?

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

추가 답변 (1개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2020년 6월 5일
편집: Sulaymon Eshkabilov 2020년 6월 5일
Here is an easy solution:
a=1;b=2;c=3;
save('myMatFile.mat','a','b','c')
% Or
a=1;b=2;c=3;
MY_var = {'a','b','c'};
save('myMatFile.mat','MY_var')
  댓글 수: 1
Stephen23
Stephen23 2020년 6월 5일
편집: Stephen23 2020년 6월 5일
This code
MY_var = {'a','b','c'};
save('myMatFile.mat','MY_var')
will just save a cell array of character vectors 'a', 'b', and 'c', not the variables with the corresponding names. This does not resolve the original question.

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

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by