Repository navigation
Expand file tree
/
Copy pathFun_SaveVars.m
More file actions
54 lines (49 loc) · 2.06 KB
/
Copy pathFun_SaveVars.m
File metadata and controls
54 lines (49 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
function Fun_SaveVars(varargin)
% Pack specified workspace variables into a structure
%
% Example: If variables a, b, c exist in the workspace, calling
% Fun_SaveVars('a','b','c','DataObs')
% creates a structure named DataObs in the caller workspace,
% with fields DataObs.a = a, DataObs.b = b, DataObs.c = c.
%
% Notes:
% - All inputs must be character vectors or string scalars.
% - If a specified variable does not exist in the caller workspace,
% a warning is issued and that variable is skipped.
% - The output structure is assigned in the caller's workspace.
% Validate number of inputs
if nargin < 2
error('At least two inputs are required: one variable name and one structure name.');
end
% Separate variable names and the target structure name
varNames = varargin(1:end-1);
structName = varargin{end};
% Validate structure name
if ~ischar(structName) && ~(isstring(structName) && isscalar(structName))
error('The last input must be a valid structure name (character vector or string scalar).');
end
structName = char(structName);
% Validate all variable name inputs
if ~all(cellfun(@(x) ischar(x) || (isstring(x) && isscalar(x)), varNames))
error('All variable name inputs must be character vectors or string scalars.');
end
% Build the structure by reading each variable from the caller workspace
S = struct();
for i = 1:numel(varNames)
varName = char(varNames{i});
% Check existence in the caller workspace
if evalin('caller', ['exist(''', varName, ''', ''var'')']) == 1
val = evalin('caller', varName);
S.(varName) = val;
else
warning('Variable ''%s'' does not exist in caller workspace; skipped.', varName);
end
end
% Assign the structure to the caller workspace with the given name
assignin('caller', structName, S);
% Inform the user
fprintf('Structure ''%s'' created with fields: %s\n', ...
structName, strjoin(fieldnames(S), ', '));
% save(structName);
evalin('caller', ['save ' structName '.mat ' structName]);
end