-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathdefcell.m
68 lines (62 loc) · 2.59 KB
/
defcell.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
function defcell(name,value)
% function DEFCELL(name,value)
%
% A function similar to DEFVAL or DEFSTRUCT which will assign the default
% 'value' to a cell array 'name'. If the workspace or function calling
% DEFCELL already has a cell variable 'name', it does not overwrite
% existing elements, but it will grow the existing cell to the size of
% the default, adding additional elements if necessary. If the named cell
% didn't exist at all, you can default it to anything you want in any
% number of dimensions. If it did exist, it will only work for up to
% two-dimensional arrays and complain otherwise.
%
% INPUT
%
% name A string with a variable name
% value The default cell array for that named variable
%
% OUTPUT:
%
% None. The cell array named 'name' will "appear as if by magic
% into your workspace or be available inside your function."
%
% See also ASSIGNIN, EVALIN, EXIST, ISEMPTY
%
% Last modified by gleggers-at-princeton.edu, 09/20/2013
% Error statement if a string is not provided as the first input (a very
% common mistake when typing quickly)
if ~ischar(name),
error(sprintf(['The first argument of DEFCELL ',...
'has to be a string with a variable name']));
end
% Always do it is our default here
si=1;
% See if a cell named 'name' already exists in the calling function. If it
% does not, skip to the end and assign 'value' to a cell 'name' in the
% calling function. If it does, then there is a preexisting cell (an
% "original value" or "OV" as it will be abbreviated) that DEFCELL is
% trying to default over, and more careful consideration is necessary
% Remember, "exist" works on strings, "iscell" works on things!
if evalin('caller',[ 'exist(''' name ''',''var'')']) == 1 ...
&& evalin('caller',[ 'iscell(' name ')'])
% Get size of the OV cell in the calling function
ovS = evalin('caller',[ 'size(' name ')']);
% Run through every element of that OV cell... (as a 2D thing)
for i = 1:ovS(1)
for j = 1:ovS(2)
% ...If an element (i,j) of that OV cell has a value, then
% replace the corresponding element (i,j) of this function's
% 'value' cell with the element from the OV cell
if evalin('caller',[ 'isempty(' name '{' num2str(i) ',' num2str(j) '})']) == 0
value{i,j} = evalin('caller',[name '{' num2str(i) ',' num2str(j) '}']);
end
end
end
else
si=logical(0);
end
% Assign this function's 'value' cell (modified or not) to variable 'name'
% in the calling function, replacing any existing variable of that name
if si
assignin('caller',name,value);
end