comparison scripts/general/structfun.m @ 10132:aa0f575cf39b

improve structfun's Matlab compatibility
author Jaroslav Hajek <highegg@gmail.com>
date Tue, 19 Jan 2010 10:06:42 +0100
parents 9d1a14e12431
children be13fa20656a
comparison
equal deleted inserted replaced
10131:30817aa3889a 10132:aa0f575cf39b
1 ## Copyright (C) 2007, 2008, 2009 David Bateman 1 ## Copyright (C) 2007, 2008, 2009 David Bateman
2 ## Copyright (C) 2010 VZLU Prague
2 ## 3 ##
3 ## This file is part of Octave. 4 ## This file is part of Octave.
4 ## 5 ##
5 ## Octave is free software; you can redistribute it and/or modify it 6 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by 7 ## under the terms of the GNU General Public License as published by
72 function varargout = structfun (fun, s, varargin); 73 function varargout = structfun (fun, s, varargin);
73 if (nargin < 2) 74 if (nargin < 2)
74 print_usage (); 75 print_usage ();
75 endif 76 endif
76 77
78 uniform_output = true;
79 uo_str = "uniformoutput";
80
81 nargs = length (varargin);
82 if (nargs >= 2 && strcmpi (varargin{1}, uo_str))
83 uniform_output =varargin{2};
84 elseif (nargs >= 4 && strcmpi (varargin{3}, uo_str))
85 uniform_output =varargin{4};
86 endif
87
77 varargout = cell (max ([nargout, 1]), 1); 88 varargout = cell (max ([nargout, 1]), 1);
78 [varargout{:}] = cellfun (fun, struct2cell (s), varargin{:}); 89 [varargout{:}] = cellfun (fun, struct2cell (s), varargin{:});
79 90
80 if (iscell (varargout{1})) 91 if (! uniform_output)
81 [varargout{:}] = cell2struct (varargout{1}, fieldnames(s), 1); 92 varargout = cellfun (@cell2struct, varargout, {fieldnames(s)}, {1}, uo_str, false);
82 endif 93 endif
83 endfunction 94 endfunction
84 95
85 96
86 %!test 97 %!test
89 %! l.name1 = "Smith"; 100 %! l.name1 = "Smith";
90 %! l.name2 = "Jones"; 101 %! l.name2 = "Jones";
91 %! o = structfun (@(x) regexp (x, '(\w+)$', "matches"){1}, s, 102 %! o = structfun (@(x) regexp (x, '(\w+)$', "matches"){1}, s,
92 %! "UniformOutput", false); 103 %! "UniformOutput", false);
93 %! assert (o, l); 104 %! assert (o, l);
105
106 %!function [a, b] = twoouts (x)
107 %! a = x + x;
108 %! b = x * x;
109
110 %!test
111 %! s = struct ("a", {1, 2, 3}, "b", {4, 5, 6});
112 %! c(1:2, 1, 1) = [2; 8];
113 %! c(1:2, 1, 2) = [4; 10];
114 %! c(1:2, 1, 3) = [6; 12];
115 %! d(1:2, 1, 1) = [1; 16];
116 %! d(1:2, 1, 2) = [4; 25];
117 %! d(1:2, 1, 3) = [9; 36];
118 %! [aa, bb] = structfun(@twoouts, s);
119 %! assert(aa, c);
120 %! assert(bb, d);
121
122 %!test
123 %! s = struct ("a", {1, 2, 3}, "b", {4, 5, 6});
124 %! c = struct ("a", {2, 4, 6}, "b", {8, 10, 12});
125 %! d = struct ("a", {1, 4, 9}, "b", {16, 25, 36});
126 %! [aa, bb] = structfun(@twoouts, s, "uniformoutput", false);
127 %! assert(aa, c);
128 %! assert(bb, d);