1 ## Copyright (C) 2009 VZLU Prague, a.s., Czech Republic
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
17 ## @deftypefn{Function File} {d =} subsasgn (d, s, val)
18 ## Overloaded subsasgn for dictionaries.
21 ## Author: Jaroslav Hajek <highegg@gmail.com>
23 function d = subsasgn (d, s, val)
25 error ("dict: missing index");
34 error ("dict: needs exactly one index");
37 ## Scalar assignment case. Search whether the key is present.
38 i = lookup (d.keys, ind, "m");
40 ## The key is present; handle the rest of chain if needed,
43 val = subsasgn (d.values{i}, s(2:end), val);
47 ## The key is missing; handle the rest of chain if needed.
49 val = subsasgn ([], s(2:end), val);
51 ## Look up the proper place to insert the new key.
52 i = lookup (d.keys, ind);
53 d.keys = [d.keys(1:i,1); {ind}; d.keys(i+1:end,1)];
55 d.values = [d.values(1:i,1); {val}; d.values(i+1:end,1)];
57 elseif (iscellstr (ind))
58 ## Multiple assignment case. Perform checks.
60 error ("chained subscripts not allowed for multiple fields");
64 i = lookup (d.keys, ind, "m");
70 val = repmat (val, size (ind));
71 elseif (numel (ind) != numel (val))
72 error ("numbers of elements of index and rhs must match");
74 ## Choose from two paths.
75 if (numel (ind) < numel (d.keys))
76 ## Scarce assignment. There's a good chance that all keys will be present.
77 i = lookup (d.keys, ind, "m");
82 d.values(i(mask)) = val(mask);
84 [d.keys, i] = sort ([d.keys; ind(mask)(:)]);
85 d.values = [d.values; val(mask)(:)](i);
88 ## Mass assignment. Probably most of the keys are new ones, so simply
90 [d.keys, i] = unique ([d.keys; ind(:)]);
91 d.values = [d.values; val(:)](i);
94 error ("expected cell rhs for cell index");
97 error ("invalid index");
100 error ("invalid subscript type for assignment");