-
Notifications
You must be signed in to change notification settings - Fork 0
/
tc_ws2struct.m
70 lines (59 loc) · 2.01 KB
/
tc_ws2struct.m
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function wsStruct=tc_ws2struct(ws,varargin)
%%
% usage:
%
% wsStruct = tc_ws2struct(ws, varargin);
%
% returns a structure from all workspace variables in workspace ws (e.g. 'base').
%
% value pairs:
%
% 'MaxVarSize', value only include variables smaller than value (in byte)
% 'Exclude', 'ans' include all variables except 'ans'
% 'Include', {'thisVar', 'andThat'} include only defined variables
%
% note that the inclusion hierarchy is according to the order in which the
% arguments were provided.
%
% example:
%
% tc_ws2struct('base', 'MaxVarSize', 4096, 'Exclude', {'ans', 'anotherVar'})
%
% returns a structure including all base workspace variables that occupy
% less than 4096 bytes of memory, but not the variables 'ans' and
% 'anotherVar'
% get workspace variable information
wsVars=evalin(ws,'whos');
% prepare index vectors for variable inclusion
includeThoseVars=ones(size({wsVars.name}));
includeThoseBasedOnSize=ones(size({wsVars.name}));
excludeThose=zeros(size({wsVars.name}));
includeThose=ones(size({wsVars.name}));
% iterate over key-value pairs
for argNum=1:2:length(varargin)
% get key value pair
key=lower(varargin{argNum});
value=varargin{argNum+1};
switch key
case 'maxvarsize'
includeThoseBasedOnSize=horzcat(wsVars.bytes)<=value;
case 'exclude'
excludeThose=ismember({wsVars.name},value);
case 'include'
includeThose=ismember({wsVars.name},value);
% if no matching key was found, but an argument was provided
otherwise
error('invalid key value')
end
end
% combine index vector for variable inclusion
includeThoseVars=(includeThoseVars&includeThoseBasedOnSize&~excludeThose&includeThose)>0;
% obtain selected workspace variable names
wsVars={wsVars.name};
wsVars=wsVars(includeThoseVars);
% obtain workspace variable values
wsVarsValues=cellfun(@(x) {evalin(ws,x)},wsVars,'unif',0);
wsStruct=[wsVars',wsVarsValues'].';
% make struct from name-value pairs
wsStruct=struct(wsStruct{:});
end