File: cellfun.cc

package info (click to toggle)
octave 4.0.3-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 94,200 kB
  • ctags: 52,925
  • sloc: cpp: 316,850; ansic: 43,469; fortran: 23,670; sh: 13,805; yacc: 8,204; objc: 7,939; lex: 3,631; java: 2,127; makefile: 1,746; perl: 1,022; awk: 988
file content (2553 lines) | stat: -rw-r--r-- 82,959 bytes parent folder | download | duplicates (2)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
/*

Copyright (C) 2005-2015 Mohamed Kamoun
Copyright (C) 2006-2015 Bill Denney
Copyright (C) 2009 Jaroslav Hajek
Copyright (C) 2010 VZLU Prague

This file is part of Octave.

Octave is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.

Octave is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with Octave; see the file COPYING.  If not, see
<http://www.gnu.org/licenses/>.

*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <vector>
#include <list>
#include <memory>

#include "caseless-str.h"
#include "lo-mappers.h"
#include "oct-locbuf.h"

#include "Cell.h"
#include "oct-map.h"
#include "defun.h"
#include "parse.h"
#include "variables.h"
#include "ov-colon.h"
#include "unwind-prot.h"
#include "gripes.h"
#include "utils.h"

#include "ov-class.h"
#include "ov-scalar.h"
#include "ov-float.h"
#include "ov-complex.h"
#include "ov-flt-complex.h"
#include "ov-bool.h"
#include "ov-int8.h"
#include "ov-int16.h"
#include "ov-int32.h"
#include "ov-int64.h"
#include "ov-uint8.h"
#include "ov-uint16.h"
#include "ov-uint32.h"
#include "ov-uint64.h"

#include "ov-fcn-handle.h"

static octave_value_list
get_output_list (octave_idx_type count, octave_idx_type nargout,
                 const octave_value_list& inputlist,
                 octave_value& func,
                 octave_value& error_handler)
{
  octave_value_list tmp;
  try
    {
      tmp = func.do_multi_index_op (nargout, inputlist);
    }
  catch (octave_execution_exception)
    {
      if (error_handler.is_defined ())
        error_state = 1;
    }

  if (error_state)
    {
      if (error_handler.is_defined ())
        {
          octave_scalar_map msg;
          msg.assign ("identifier", last_error_id ());
          msg.assign ("message", last_error_message ());
          msg.assign ("index",
                      static_cast<double> (count
                                           + static_cast<octave_idx_type>(1)));

          octave_value_list errlist = inputlist;
          errlist.prepend (msg);

          buffer_error_messages--;

          error_state = 0;

          tmp = error_handler.do_multi_index_op (nargout, errlist);

          buffer_error_messages++;

          if (error_state)
            tmp.clear ();
        }
      else
        tmp.clear ();
    }

  return tmp;
}

// Templated function because the user can be stubborn enough to request
// a cell array as an output even in these cases where the output fits
// in an ordinary array
template<typename BNDA, typename NDA>
static octave_value_list
try_cellfun_internal_ops (const octave_value_list& args, int nargin)
{
  octave_value_list retval;

  std::string name = args(0).string_value ();

  const Cell f_args = args(1).cell_value ();

  octave_idx_type k = f_args.numel ();

  if (name == "isempty")
    {
      BNDA result (f_args.dims ());
      for (octave_idx_type count = 0; count < k; count++)
        result(count) = f_args.elem (count).is_empty ();
      retval(0) = result;
    }
  else if (name == "islogical")
    {
      BNDA result (f_args.dims ());
      for (octave_idx_type  count= 0; count < k; count++)
        result(count) = f_args.elem (count).is_bool_type ();
      retval(0) = result;
    }
  else if (name == "isnumeric")
    {
      BNDA result (f_args.dims ());
      for (octave_idx_type  count= 0; count < k; count++)
        result(count) = f_args.elem (count).is_numeric_type ();
      retval(0) = result;
    }
  else if (name == "isreal")
    {
      BNDA result (f_args.dims ());
      for (octave_idx_type  count= 0; count < k; count++)
        result(count) = f_args.elem (count).is_real_type ();
      retval(0) = result;
    }
  else if (name == "length")
    {
      NDA result (f_args.dims ());
      for (octave_idx_type  count= 0; count < k; count++)
        result(count) = static_cast<double> (f_args.elem (count).length ());
      retval(0) = result;
    }
  else if (name == "ndims")
    {
      NDA result (f_args.dims ());
      for (octave_idx_type count = 0; count < k; count++)
        result(count) = static_cast<double> (f_args.elem (count).ndims ());
      retval(0) = result;
    }
  else if (name == "numel" || name == "prodofsize")
    {
      NDA result (f_args.dims ());
      for (octave_idx_type count = 0; count < k; count++)
        result(count) = static_cast<double> (f_args.elem (count).numel ());
      retval(0) = result;
    }
  else if (name == "size")
    {
      if (nargin == 3)
        {
          int d = args(2).nint_value () - 1;

          if (d < 0)
            error ("cellfun: K must be a positive integer");

          if (! error_state)
            {
              NDA result (f_args.dims ());
              for (octave_idx_type count = 0; count < k; count++)
                {
                  dim_vector dv = f_args.elem (count).dims ();
                  if (d < dv.length ())
                    result(count) = static_cast<double> (dv(d));
                  else
                    result(count) = 1.0;
                }
              retval(0) = result;
            }
        }
      else
        error ("cellfun: not enough arguments for \"size\"");
    }
  else if (name == "isclass")
    {
      if (nargin == 3)
        {
          std::string class_name = args(2).string_value ();
          BNDA result (f_args.dims ());
          for (octave_idx_type count = 0; count < k; count++)
            result(count) = (f_args.elem (count).class_name () == class_name);

          retval(0) = result;
        }
      else
        error ("cellfun: not enough arguments for \"isclass\"");
    }

  return retval;
}

static void
get_mapper_fun_options (const octave_value_list& args, int& nargin,
                        bool& uniform_output, octave_value& error_handler)
{
  while (nargin > 3 && args(nargin-2).is_string ())
    {
      caseless_str arg = args(nargin-2).string_value ();

      size_t compare_len = std::max (arg.length (), static_cast<size_t> (2));

      if (arg.compare ("uniformoutput", compare_len))
        uniform_output = args(nargin-1).bool_value ();
      else if (arg.compare ("errorhandler", compare_len))
        {
          if (args(nargin-1).is_function_handle ()
              || args(nargin-1).is_inline_function ())
            {
              error_handler = args(nargin-1);
            }
          else if (args(nargin-1).is_string ())
            {
              std::string err_name = args(nargin-1).string_value ();

              error_handler = symbol_table::find_function (err_name);

              if (error_handler.is_undefined ())
                {
                  error ("cellfun: invalid function NAME: %s",
                         err_name.c_str ());
                  break;
                }
            }
          else
            {
              error ("cellfun: invalid value for 'ErrorHandler' function");
              break;
            }
        }
      else
        {
          error ("cellfun: unrecognized parameter %s",
                 arg.c_str ());
          break;
        }

      nargin -= 2;
    }

  nargin -= 1;
}

DEFUN (cellfun, args, nargout,
       "-*- texinfo -*-\n\
@deftypefn  {Built-in Function} {} cellfun (@var{name}, @var{C})\n\
@deftypefnx {Built-in Function} {} cellfun (\"size\", @var{C}, @var{k})\n\
@deftypefnx {Built-in Function} {} cellfun (\"isclass\", @var{C}, @var{class})\n\
@deftypefnx {Built-in Function} {} cellfun (@var{func}, @var{C})\n\
@deftypefnx {Built-in Function} {} cellfun (@var{func}, @var{C}, @var{D})\n\
@deftypefnx {Built-in Function} {[@var{a}, @dots{}] =} cellfun (@dots{})\n\
@deftypefnx {Built-in Function} {} cellfun (@dots{}, \"ErrorHandler\", @var{errfunc})\n\
@deftypefnx {Built-in Function} {} cellfun (@dots{}, \"UniformOutput\", @var{val})\n\
\n\
Evaluate the function named @var{name} on the elements of the cell array\n\
@var{C}.\n\
\n\
Elements in @var{C} are passed on to the named function individually.  The\n\
function @var{name} can be one of the functions\n\
\n\
@table @code\n\
@item isempty\n\
Return 1 for empty elements.\n\
\n\
@item islogical\n\
Return 1 for logical elements.\n\
\n\
@item isnumeric\n\
Return 1 for numeric elements.\n\
\n\
@item isreal\n\
Return 1 for real elements.\n\
\n\
@item length\n\
Return a vector of the lengths of cell elements.\n\
\n\
@item ndims\n\
Return the number of dimensions of each element.\n\
\n\
@item  numel\n\
@itemx prodofsize\n\
Return the number of elements contained within each cell element.  The\n\
number is the product of the dimensions of the object at each cell element.\n\
\n\
@item size\n\
Return the size along the @var{k}-th dimension.\n\
\n\
@item isclass\n\
Return 1 for elements of @var{class}.\n\
@end table\n\
\n\
Additionally, @code{cellfun} accepts an arbitrary function @var{func}\n\
in the form of an inline function, function handle, or the name of a\n\
function (in a character string).  The function can take one or more\n\
arguments, with the inputs arguments given by @var{C}, @var{D}, etc.\n\
Equally the function can return one or more output arguments.  For example:\n\
\n\
@example\n\
@group\n\
cellfun (\"atan2\", @{1, 0@}, @{0, 1@})\n\
     @result{} [ 1.57080   0.00000 ]\n\
@end group\n\
@end example\n\
\n\
The number of output arguments of @code{cellfun} matches the number of output\n\
arguments of the function.  The outputs of the function will be collected\n\
into the output arguments of @code{cellfun} like this:\n\
\n\
@example\n\
@group\n\
function [a, b] = twoouts (x)\n\
  a = x;\n\
  b = x*x;\n\
endfunction\n\
[aa, bb] = cellfun (@@twoouts, @{1, 2, 3@})\n\
     @result{}\n\
        aa =\n\
           1 2 3\n\
        bb =\n\
           1 4 9\n\
@end group\n\
@end example\n\
\n\
Note that per default the output argument(s) are arrays of the same size as\n\
the input arguments.  Input arguments that are singleton (1x1) cells will be\n\
automatically expanded to the size of the other arguments.\n\
\n\
If the parameter @qcode{\"UniformOutput\"} is set to true (the default),\n\
then the function must return scalars which will be concatenated into the\n\
return array(s).  If @qcode{\"UniformOutput\"} is false, the outputs are\n\
concatenated into a cell array (or cell arrays).  For example:\n\
\n\
@example\n\
@group\n\
cellfun (\"tolower\", @{\"Foo\", \"Bar\", \"FooBar\"@},\n\
         \"UniformOutput\", false)\n\
@result{} @{\"foo\", \"bar\", \"foobar\"@}\n\
@end group\n\
@end example\n\
\n\
Given the parameter @qcode{\"ErrorHandler\"}, then @var{errfunc} defines a\n\
function to call in case @var{func} generates an error.  The form of the\n\
function is\n\
\n\
@example\n\
function [@dots{}] = errfunc (@var{s}, @dots{})\n\
@end example\n\
\n\
@noindent\n\
where there is an additional input argument to @var{errfunc} relative to\n\
@var{func}, given by @var{s}.  This is a structure with the elements\n\
@qcode{\"identifier\"}, @qcode{\"message\"} and @qcode{\"index\"}, giving\n\
respectively the error identifier, the error message, and the index into the\n\
input arguments of the element that caused the error.  For example:\n\
\n\
@example\n\
@group\n\
function y = foo (s, x), y = NaN; endfunction\n\
cellfun (\"factorial\", @{-1,2@}, \"ErrorHandler\", @@foo)\n\
@result{} [NaN 2]\n\
@end group\n\
@end example\n\
\n\
Use @code{cellfun} intelligently.  The @code{cellfun} function is a\n\
useful tool for avoiding loops.  It is often used with anonymous\n\
function handles; however, calling an anonymous function involves an\n\
overhead quite comparable to the overhead of an m-file function.\n\
Passing a handle to a built-in function is faster, because the\n\
interpreter is not involved in the internal loop.  For example:\n\
\n\
@example\n\
@group\n\
a = @{@dots{}@}\n\
v = cellfun (@@(x) det (x), a); # compute determinants\n\
v = cellfun (@@det, a); # faster\n\
@end group\n\
@end example\n\
\n\
@seealso{arrayfun, structfun, spfun}\n\
@end deftypefn")
{
  octave_value_list retval;
  int nargin = args.length ();
  int nargout1 = (nargout < 1 ? 1 : nargout);

  if (nargin < 2)
    {
      error ("cellfun: function requires at least 2 arguments");
      print_usage ();
      return retval;
    }

  octave_value func = args(0);

  if (! args(1).is_cell ())
    {
      error ("cellfun: C must be a cell array");

      return retval;
    }

  if (func.is_string ())
    {
      retval = try_cellfun_internal_ops<boolNDArray,NDArray>(args, nargin);

      if (error_state || ! retval.empty ())
        return retval;

      // See if we can convert the string into a function.

      std::string name = args(0).string_value ();

      if (! valid_identifier (name))
        {
          std::string fcn_name = unique_symbol_name ("__cellfun_fcn__");
          std::string fname = "function y = " + fcn_name + "(x) y = ";

          octave_function *ptr_func
            = extract_function (args(0), "cellfun", fcn_name,
                                fname, "; endfunction");

          if (ptr_func && ! error_state)
            func = octave_value (ptr_func, true);
        }
      else
        {
          func = symbol_table::find_function (name);

          if (func.is_undefined ())
            error ("cellfun: invalid function NAME: %s", name.c_str ());
        }

      if (error_state || ! retval.empty ())
        return retval;
    }

  if (func.is_function_handle () || func.is_inline_function ()
      || func.is_function ())
    {

      bool uniform_output = true;
      octave_value error_handler;

      get_mapper_fun_options (args, nargin, uniform_output, error_handler);

      // The following is an optimisation because the symbol table can
      // give a more specific function class, so this can result in
      // fewer polymorphic function calls as the function gets called
      // for each value of the array.
      {
        if (func.is_function_handle ())
          {
            octave_fcn_handle* f = func.fcn_handle_value ();

            // Overloaded function handles need to check the type of the
            // arguments for each element of the array, so they cannot
            // be optimised this way.
            if (f -> is_overloaded ())
              goto nevermind;
          }

        std::string name = func.function_value () -> name ();
        octave_value f = symbol_table::find_function (name);

        if (f.is_defined ())
          {
            //Except for these two which are special cases...
            if (name != "size" && name != "class")
              {
                //Try first the optimised code path for built-in functions
                octave_value_list tmp_args = args;
                tmp_args(0) = name;

                if (uniform_output)
                  retval =
                    try_cellfun_internal_ops<boolNDArray, NDArray> (tmp_args,
                                                                    nargin);
                else
                  retval =
                    try_cellfun_internal_ops<Cell, Cell> (tmp_args, nargin);

                if (error_state || ! retval.empty ())
                  return retval;
              }

            //Okay, we tried, doesn't work, let's do the best we can
            //instead and avoid polymorphic calls for each element of
            //the array.
            func = f;
          }
      }
    nevermind:

      if (error_state)
        return octave_value_list ();

      // Extract cell arguments.

      octave_value_list inputlist (nargin, octave_value ());

      OCTAVE_LOCAL_BUFFER (Cell, inputs, nargin);
      OCTAVE_LOCAL_BUFFER (bool, mask, nargin);

      // This is to prevent copy-on-write.
      const Cell *cinputs = inputs;

      octave_idx_type k = 1;

      dim_vector fdims (1, 1);

      // Collect arguments.  Pre-fill scalar elements of inputlist
      // array.

      for (int j = 0; j < nargin; j++)
        {
          if (! args(j+1).is_cell ())
            {
              error ("cellfun: arguments must be cells");
              return octave_value_list ();
            }

          inputs[j] = args(j+1).cell_value ();
          mask[j] = inputs[j].numel () != 1;
          if (! mask[j])
            inputlist(j) = cinputs[j](0);
        }

      for (int j = 0; j < nargin; j++)
        {
          if (mask[j])
            {
              fdims = inputs[j].dims ();
              k = inputs[j].numel ();
              for (int i = j+1; i < nargin; i++)
                {
                  if (mask[i] && inputs[i].dims () != fdims)
                    {
                      error ("cellfun: dimensions mismatch");
                      return octave_value_list ();
                    }
                }
              break;
            }
        }

      unwind_protect frame;
      frame.protect_var (buffer_error_messages);

      if (error_handler.is_defined ())
        buffer_error_messages++;

      // Apply functions.

      if (uniform_output)
        {
          std::list<octave_value_list> idx_list (1);
          idx_list.front ().resize (1);
          std::string idx_type = "(";

          OCTAVE_LOCAL_BUFFER (octave_value, retv, nargout1);

          for (octave_idx_type count = 0; count < k; count++)
            {
              for (int j = 0; j < nargin; j++)
                {
                  if (mask[j])
                    inputlist.xelem (j) = cinputs[j](count);
                }

              const octave_value_list tmp
                = get_output_list (count, nargout, inputlist, func,
                                   error_handler);

              if (error_state)
                return retval;

              if (nargout > 0 && tmp.length () < nargout)
                {
                  error ("cellfun: function returned fewer than nargout values");
                  return retval;
                }

              if  (nargout > 0
                   || (nargout == 0
                       && tmp.length () > 0 && tmp(0).is_defined ()))
                {
                  int num_to_copy = tmp.length ();

                  if (num_to_copy > nargout1)
                    num_to_copy = nargout1;

                  if (count == 0)
                    {
                      for (int j = 0; j < num_to_copy; j++)
                        {
                          if (tmp(j).is_defined ())
                            {
                              octave_value val = tmp(j);

                              if (val.numel () == 1)
                                retv[j] = val.resize (fdims);
                              else
                                {
                                  error ("cellfun: all values must be scalars when UniformOutput = true");
                                  break;
                                }
                            }
                        }
                    }
                  else
                    {
                      for (int j = 0; j < num_to_copy; j++)
                        {
                          if (tmp(j).is_defined ())
                            {
                              octave_value val = tmp(j);

                              if (! retv[j].fast_elem_insert (count, val))
                                {
                                  if (val.numel () == 1)
                                    {
                                      idx_list.front ()(0) = count + 1.0;
                                      retv[j].assign (octave_value::op_asn_eq,
                                                      idx_type, idx_list, val);

                                      if (error_state)
                                        break;
                                    }
                                  else
                                    {
                                      error ("cellfun: all values must be scalars when UniformOutput = true");
                                      break;
                                    }
                                }
                            }
                        }
                    }
                }

              if (error_state)
                break;
            }

          retval.resize (nargout1);

          for (int j = 0; j < nargout1; j++)
            {
              if (nargout > 0 && retv[j].is_undefined ())
                retval(j) = NDArray (fdims);
              else
                retval(j) = retv[j];
            }
        }
      else
        {
          OCTAVE_LOCAL_BUFFER (Cell, results, nargout1);

          for (int j = 0; j < nargout1; j++)
            results[j].resize (fdims, Matrix ());

          bool have_some_output = false;

          for (octave_idx_type count = 0; count < k; count++)
            {
              for (int j = 0; j < nargin; j++)
                {
                  if (mask[j])
                    inputlist.xelem (j) = cinputs[j](count);
                }

              const octave_value_list tmp
                = get_output_list (count, nargout, inputlist, func,
                                   error_handler);

              if (error_state)
                return retval;

              if (nargout > 0 && tmp.length () < nargout)
                {
                  error ("cellfun: function returned fewer than nargout values");
                  return retval;
                }

              if  (nargout > 0
                   || (nargout == 0
                       && tmp.length () > 0 && tmp(0).is_defined ()))
                {
                  int num_to_copy = tmp.length ();

                  if (num_to_copy > nargout1)
                    num_to_copy = nargout1;

                  if (num_to_copy > 0)
                    have_some_output = true;

                  for (int j = 0; j < num_to_copy; j++)
                    results[j](count) = tmp(j);
                }
            }

          if (have_some_output || fdims.any_zero ())
            {
              retval.resize (nargout1);

              for (int j = 0; j < nargout1; j++)
                retval(j) = results[j];
            }
        }
    }
  else
    error ("cellfun: argument NAME must be a string or function handle");

  return retval;
}

/*

%!function r = __f11 (x)
%!  global __cellfun_test_num_outputs__;
%!  __cellfun_test_num_outputs__ = nargout;
%!  r = x;
%!endfunction

%!function __f01 (x)
%!  global __cellfun_test_num_outputs__;
%!  __cellfun_test_num_outputs__ = nargout;
%!endfunction

%!test
%! global __cellfun_test_num_outputs__;
%! cellfun (@__f11, {1});
%! assert (__cellfun_test_num_outputs__, 0);
%! x = cellfun (@__f11, {1});
%! assert (__cellfun_test_num_outputs__, 1);

%!test
%! global __cellfun_test_num_outputs__;
%! cellfun (@__f01, {1});
%! assert (__cellfun_test_num_outputs__, 0);

%!error x = cellfun (@__f01, {1, 2});

%!test
%! assert (cellfun (@__f11, {1, 2}), [1, 2]);
%! assert (cellfun (@__f11, {1, 2}, 'uniformoutput', false), {1, 2});

%!test
%! [a,b] = cellfun (@(x) x, cell (2, 0));
%! assert (a, zeros (2, 0));
%! assert (b, zeros (2, 0));

%!test
%! [a,b] = cellfun (@(x) x, cell (2, 0), "uniformoutput", false);
%! assert (a, cell (2, 0));
%! assert (b, cell (2, 0));

%% Test function to check the "Errorhandler" option
%!function z = __cellfunerror (S, varargin)
%!  z = S;
%!endfunction

%% First input argument can be a string, an inline function,
%% a function_handle or an anonymous function
%!test
%! A = cellfun ("islogical", {true, 0.1, false, i*2});
%! assert (A, [true, false, true, false]);
%!test
%! A = cellfun (inline ("islogical (x)", "x"), {true, 0.1, false, i*2});
%! assert (A, [true, false, true, false]);
%!test
%! A = cellfun (@islogical, {true, 0.1, false, i*2});
%! assert (A, [true, false, true, false]);
%!test
%! A = cellfun (@(x) islogical (x), {true, 0.1, false, i*2});
%! assert (A, [true, false, true, false]);

%% First input argument can be the special string "isreal",
%% "isempty", "islogical", "isnumeric", "length", "ndims" or "prodofsize"
%!test
%! A = cellfun ("isreal", {true, 0.1, {}, i*2, [], "abc"});
%! assert (A, [true, true, false, false, true, true]);
%!test
%! A = cellfun ("isempty", {true, 0.1, false, i*2, [], "abc"});
%! assert (A, [false, false, false, false, true, false]);
%!test
%! A = cellfun ("islogical", {true, 0.1, false, i*2, [], "abc"});
%! assert (A, [true, false, true, false, false, false]);
%!test
%! A = cellfun ("isnumeric", {true, 0.1, false, i*2, [], "abc"});
%! assert (A, [false, true, false, true, true, false]);
%!test
%! A = cellfun ("length", {true, 0.1, false, i*2, [], "abc"});
%! assert (A, [1, 1, 1, 1, 0, 3]);
%!test
%! A = cellfun ("ndims", {[1, 2; 3, 4]; (cell (1,2,3,4))});
%! assert (A, [2; 4]);
%!test
%! A = cellfun ("prodofsize", {[1, 2; 3, 4], (cell (1,2,3,4))});
%! assert (A, [4, 24]);

%% Number of input and output arguments may not be limited to one
%!test
%! A = cellfun (@(x,y,z) x + y + z, {1, 1, 1}, {2, 2, 2}, {3, 4, 5});
%! assert (A, [6, 7, 8]);
%!test
%! A = cellfun (@(x,y,z) x + y + z, {1, 1, 1}, {2, 2, 2}, {3, 4, 5}, ...
%!              "UniformOutput", false);
%! assert (A, {6, 7, 8});
%!test %% Two input arguments of different types
%! A = cellfun (@(x,y) islogical (x) && ischar (y), {false, true}, {"a", 3});
%! assert (A, [true, false]);
%!test %% Pass another variable to the anonymous function
%! y = true;
%! A = cellfun (@(x) islogical (x) && y, {false, 0.3});
%! assert (A, [true, false]);
%!test %% Three ouptut arguments of different type
%! [A, B, C] = cellfun (@find, {10, 11; 0, 12}, "UniformOutput", false);
%! assert (isequal (A, {true, true; [], true}));
%! assert (isequal (B, {true, true; [], true}));
%! assert (isequal (C, {10, 11; [], 12}));

%% Input arguments can be of type cell array of logical
%!test
%! A = cellfun (@(x,y) x == y, {false, true}, {true, true});
%! assert (A, [false, true]);
%!test
%! A = cellfun (@(x,y) x == y, {false; true}, {true; true}, ...
%!              "UniformOutput", true);
%! assert (A, [false; true]);
%!test
%! A = cellfun (@(x) x, {false, true; false, true}, "UniformOutput", false);
%! assert (A, {false, true; false, true});
%!test %% Three ouptut arguments of same type
%! [A, B, C] = cellfun (@find, {true, false; false, true}, ...
%!                      "UniformOutput", false);
%! assert (isequal (A, {true, []; [], true}));
%! assert (isequal (B, {true, []; [], true}));
%! assert (isequal (C, {true, []; [], true}));
%!test
%! A = cellfun (@(x,y) cell2str (x,y), {true}, {true}, ...
%!              "ErrorHandler", @__cellfunerror);
%! assert (isfield (A, "identifier"), true);
%! assert (isfield (A, "message"), true);
%! assert (isfield (A, "index"), true);
%! assert (isempty (A.message), false);
%! assert (A.index, 1);
%!test %% Overwriting setting of "UniformOutput" true
%! A = cellfun (@(x,y) cell2str (x,y), {true}, {true}, ...
%!              "UniformOutput", true, "ErrorHandler", @__cellfunerror);
%! assert (isfield (A, "identifier"), true);
%! assert (isfield (A, "message"), true);
%! assert (isfield (A, "index"), true);
%! assert (isempty (A.message), false);
%! assert (A.index, 1);

%% Input arguments can be of type cell array of numeric
%!test
%! A = cellfun (@(x,y) x>y, {1.1, 4.2}, {3.1, 2+3*i});
%! assert (A, [false, true]);
%!test
%! A = cellfun (@(x,y) x>y, {1.1, 4.2; 2, 4}, {3.1, 2; 2, 4+2*i}, ...
%!              "UniformOutput", true);
%! assert (A, [false, true; false, false]);
%!test
%! A = cellfun (@(x,y) x:y, {1.1, 4}, {3.1, 6}, "UniformOutput", false);
%! assert (isequal (A{1}, [1.1, 2.1, 3.1]));
%! assert (isequal (A{2}, [4, 5, 6]));
%!test %% Three ouptut arguments of different type
%! [A, B, C] = cellfun (@find, {10, 11; 0, 12}, "UniformOutput", false);
%! assert (isequal (A, {true, true; [], true}));
%! assert (isequal (B, {true, true; [], true}));
%! assert (isequal (C, {10, 11; [], 12}));
%!test
%! A = cellfun (@(x,y) cell2str (x,y), {1.1, 4}, {3.1, 6}, ...
%!              "ErrorHandler", @__cellfunerror);
%! B = isfield (A(1), "message") && isfield (A(1), "index");
%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
%! assert ([A(1).index, A(2).index], [1, 2]);
%!test %% Overwriting setting of "UniformOutput" true
%! A = cellfun (@(x,y) cell2str (x,y), {1.1, 4}, {3.1, 6}, ...
%!              "UniformOutput", true, "ErrorHandler", @__cellfunerror);
%! B = isfield (A(1), "message") && isfield (A(1), "index");
%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
%! assert ([A(1).index, A(2).index], [1, 2]);

%% Input arguments can be of type cell arrays of character or strings
%!error %% "UniformOutput" false should be used
%! A = cellfun (@(x,y) x>y, {"ad", "c", "ghi"}, {"cc", "d", "fgh"});
%!test
%! A = cellfun (@(x,y) x>y, {"a"; "f"}, {"c"; "d"}, "UniformOutput", true);
%! assert (A, [false; true]);
%!test
%! A = cellfun (@(x,y) x:y, {"a", "d"}, {"c", "f"}, "UniformOutput", false);
%! assert (A, {"abc", "def"});
%!test
%! A = cellfun (@(x,y) cell2str (x,y), {"a", "d"}, {"c", "f"}, ...
%!              "ErrorHandler", @__cellfunerror);
%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
%! assert ([A(1).index, A(2).index], [1, 2]);
%!test %% Overwriting setting of "UniformOutput" true
%! A = cellfun (@(x,y) cell2str (x,y), {"a", "d"}, {"c", "f"}, ...
%!              "UniformOutput", true, "ErrorHandler", @__cellfunerror);
%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
%! assert ([A(1).index, A(2).index], [1, 2]);

%% Structures cannot be handled by cellfun
%!error
%! vst1.a = 1.1;  vst1.b = 4.2;  vst2.a = 3.1;  vst2.b = 2;
%! A = cellfun (@(x,y) (x.a < y.a) && (x.b > y.b), vst1, vst2);

%% Input arguments can be of type cell array of cell arrays
%!test
%! A = cellfun (@(x,y) x{1} < y{1}, {{1.1}, {4.2}}, {{3.1}, {2}});
%! assert (A, [1, 0], 1e-16);
%!test
%! A = cellfun (@(x,y) x{1} < y{1}, {{1.1}; {4.2}}, {{3.1}; {2}}, ...
%!              "UniformOutput", true);
%! assert (A, [1; 0], 1e-16);
%!test
%! A = cellfun (@(x,y) x{1} < y{1}, {{1.1}, {4.2}}, {{3.1}, {2}}, ...
%!              "UniformOutput", false);
%! assert (A, {true, false});
%!test
%! A = cellfun (@(x,y) mat2str (x,y), {{1.1}, {4.2}}, {{3.1}, {2}}, ...
%!              "ErrorHandler", @__cellfunerror);
%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
%! assert ([A(1).index, A(2).index], [1, 2]);
%!test %% Overwriting setting of "UniformOutput" true
%! A = cellfun (@(x,y) mat2str (x,y), {{1.1}, {4.2}}, {{3.1}, {2}}, ...
%!              "UniformOutput", true, "ErrorHandler", @__cellfunerror);
%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
%! assert ([A(1).index, A(2).index], [1, 2]);

%% Input arguments can be of type cell array of structure arrays
%!test
%! a = struct ("a", 1, "b", 2);  b = struct ("a", 1, "b", 3);
%! A = cellfun (@(x,y) (x.a == y.a) && (x.b < y.b), {a}, {b});
%! assert (A, true);
%!test
%! a = struct ("a", 1, "b", 2);  b = struct ("a", 1, "b", 3);
%! A = cellfun (@(x,y) (x.a == y.a) && (x.b < y.b) , {a}, {b}, ...
%!              "UniformOutput", true);
%! assert (A, true);
%!test
%! a = struct ("a", 1, "b", 2);  b = struct ("a", 1, "b", 3);
%! A = cellfun (@(x,y) (x.a == y.a) && (x.b < y.b) , {a}, {b}, ...
%!              "UniformOutput", false);
%! assert (A, {true});
%!test
%! a = struct ("a", 1, "b", 2);  b = struct ("a", 1, "b", 3);
%! A = cellfun (@(x,y) cell2str (x.a, y.a), {a}, {b}, ...
%!              "ErrorHandler", @__cellfunerror);
%! assert (isfield (A, "identifier"), true);
%! assert (isfield (A, "message"), true);
%! assert (isfield (A, "index"), true);
%! assert (isempty (A.message), false);
%! assert (A.index, 1);
%!test %% Overwriting setting of "UniformOutput" true
%! a = struct ("a", 1, "b", 2);  b = struct ("a", 1, "b", 3);
%! A = cellfun (@(x,y) cell2str (x.a, y.a), {a}, {b}, ...
%!              "UniformOutput", true, "ErrorHandler", @__cellfunerror);
%! assert (isfield (A, "identifier"), true);
%! assert (isfield (A, "message"), true);
%! assert (isfield (A, "index"), true);
%! assert (isempty (A.message), false);
%! assert (A.index, 1);

%% A lot of other tests
%!assert (cellfun (@sin, {0,1}), sin ([0,1]))
%!assert (cellfun (inline ("sin (x)"), {0,1}), sin ([0,1]))
%!assert (cellfun ("sin", {0,1}), sin ([0,1]))
%!assert (cellfun ("isempty", {1,[]}), [false,true])
%!assert (cellfun ("islogical", {false,pi}), [true,false])
%!assert (cellfun ("isnumeric", {false,pi,struct()}), [false,true,false])
%!assert (cellfun ("isreal", {1i,1}), [false,true])
%!assert (cellfun ("length", {zeros(2,2),1}), [2,1])
%!assert (cellfun ("prodofsize", {zeros(2,2),1}), [4,1])
%!assert (cellfun ("ndims", {zeros([2,2,2]),1}), [3,2])
%!assert (cellfun ("isclass", {zeros([2,2,2]),"test"}, "double"), [true,false])
%!assert (cellfun ("size", {zeros([1,2,3]),1}, 1), [1,1])
%!assert (cellfun ("size", {zeros([1,2,3]),1}, 2), [2,1])
%!assert (cellfun ("size", {zeros([1,2,3]),1}, 3), [3,1])
%!assert (cellfun (@atan2, {1,1}, {1,2}), [atan2(1,1), atan2(1,2)])
%!assert (cellfun (@atan2, {1,1}, {1,2},"UniformOutput", false), {atan2(1,1), atan2(1,2)})
%!assert (cellfun (@sin, {1,2;3,4}), sin ([1,2;3,4]))
%!assert (cellfun (@atan2, {1,1;1,1}, {1,2;1,2}), atan2 ([1,1;1,1],[1,2;1,2]))
%!error cellfun (@factorial, {-1,3})
%!assert (cellfun (@factorial,{-1,3},"ErrorHandler",@(x,y) NaN), [NaN,6])
%!assert (cellfun (@(x) x(2),{[1],[1,2]},"ErrorHandler",@(x,y) NaN), [NaN,2])
%!test
%! [a,b,c] = cellfun (@fileparts, {fullfile("a","b","c.d"), fullfile("e","f","g.h")}, "UniformOutput", false);
%! assert (a, {fullfile("a","b"), fullfile("e","f")});
%! assert (b, {"c", "g"});
%! assert (c, {".d", ".h"});

## Tests for bug #40467
%!assert (cellfun (@isreal, {1 inf nan []}), [true, true, true, true]);
%!assert (cellfun (@isreal, {1 inf nan []}, "UniformOutput", false), {true, true, true, true});
%!assert (cellfun (@iscomplex, {1 inf nan []}), [false, false, false, false]);
%!assert (cellfun (@iscomplex, {1 inf nan []}, "UniformOutput", false), {false, false, false, false});

%!error cellfun (1)
%!error cellfun ("isclass", 1)
%!error cellfun ("size", 1)
%!error cellfun (@sin, {[]}, "BadParam", false)
%!error cellfun (@sin, {[]}, "UniformOuput")
%!error cellfun (@sin, {[]}, "ErrorHandler")
*/

// Arrayfun was originally a .m file written by Bill Denney and Jaroslav
// Hajek.  It was converted to C++ by jwe so that it could properly
// handle the nargout = 0 case.

DEFUN (arrayfun, args, nargout,
       "-*- texinfo -*-\n\
@deftypefn  {Function File} {} arrayfun (@var{func}, @var{A})\n\
@deftypefnx {Function File} {@var{x} =} arrayfun (@var{func}, @var{A})\n\
@deftypefnx {Function File} {@var{x} =} arrayfun (@var{func}, @var{A}, @var{b}, @dots{})\n\
@deftypefnx {Function File} {[@var{x}, @var{y}, @dots{}] =} arrayfun (@var{func}, @var{A}, @dots{})\n\
@deftypefnx {Function File} {} arrayfun (@dots{}, \"UniformOutput\", @var{val})\n\
@deftypefnx {Function File} {} arrayfun (@dots{}, \"ErrorHandler\", @var{errfunc})\n\
\n\
Execute a function on each element of an array.\n\
\n\
This is useful for functions that do not accept array arguments.  If the\n\
function does accept array arguments it is better to call the function\n\
directly.\n\
\n\
The first input argument @var{func} can be a string, a function\n\
handle, an inline function, or an anonymous function.  The input\n\
argument @var{A} can be a logic array, a numeric array, a string\n\
array, a structure array, or a cell array.  By a call of the function\n\
@command{arrayfun} all elements of @var{A} are passed on to the named\n\
function @var{func} individually.\n\
\n\
The named function can also take more than two input arguments, with\n\
the input arguments given as third input argument @var{b}, fourth\n\
input argument @var{c}, @dots{}  If given more than one array input\n\
argument then all input arguments must have the same sizes, for\n\
example:\n\
\n\
@example\n\
@group\n\
arrayfun (@@atan2, [1, 0], [0, 1])\n\
     @result{} [ 1.5708   0.0000 ]\n\
@end group\n\
@end example\n\
\n\
If the parameter @var{val} after a further string input argument\n\
@qcode{\"UniformOutput\"} is set @code{true} (the default), then the named\n\
function @var{func} must return a single element which then will be\n\
concatenated into the return value and is of type matrix.  Otherwise,\n\
if that parameter is set to @code{false}, then the outputs are\n\
concatenated in a cell array.  For example:\n\
\n\
@example\n\
@group\n\
arrayfun (@@(x,y) x:y, \"abc\", \"def\", \"UniformOutput\", false)\n\
@result{}\n\
   @{\n\
     [1,1] = abcd\n\
     [1,2] = bcde\n\
     [1,3] = cdef\n\
   @}\n\
@end group\n\
@end example\n\
\n\
If more than one output arguments are given then the named function\n\
must return the number of return values that also are expected, for\n\
example:\n\
\n\
@example\n\
@group\n\
[A, B, C] = arrayfun (@@find, [10; 0], \"UniformOutput\", false)\n\
@result{}\n\
A =\n\
@{\n\
   [1,1] =  1\n\
   [2,1] = [](0x0)\n\
@}\n\
B =\n\
@{\n\
   [1,1] =  1\n\
   [2,1] = [](0x0)\n\
@}\n\
C =\n\
@{\n\
   [1,1] =  10\n\
   [2,1] = [](0x0)\n\
@}\n\
@end group\n\
@end example\n\
\n\
If the parameter @var{errfunc} after a further string input argument\n\
@qcode{\"ErrorHandler\"} is another string, a function handle, an inline\n\
function, or an anonymous function, then @var{errfunc} defines a\n\
function to call in the case that @var{func} generates an error.\n\
The definition of the function must be of the form\n\
\n\
@example\n\
function [@dots{}] = errfunc (@var{s}, @dots{})\n\
@end example\n\
\n\
@noindent\n\
where there is an additional input argument to @var{errfunc}\n\
relative to @var{func}, given by @var{s}.  This is a structure with\n\
the elements @qcode{\"identifier\"}, @qcode{\"message\"}, and\n\
@qcode{\"index\"} giving, respectively, the error identifier, the error\n\
message, and the index of the array elements that caused the error.  The\n\
size of the output argument of @var{errfunc} must have the same size as the\n\
output argument of @var{func}, otherwise a real error is thrown.  For\n\
example:\n\
\n\
@example\n\
@group\n\
function y = ferr (s, x), y = \"MyString\"; endfunction\n\
arrayfun (@@str2num, [1234],\n\
          \"UniformOutput\", false, \"ErrorHandler\", @@ferr)\n\
@result{}\n\
   @{\n\
     [1,1] = MyString\n\
   @}\n\
@end group\n\
@end example\n\
\n\
@seealso{spfun, cellfun, structfun}\n\
@end deftypefn")
{
  octave_value_list retval;
  int nargin = args.length ();
  int nargout1 = (nargout < 1 ? 1 : nargout);

  if (nargin < 2)
    {
      error_with_id ("Octave:invalid-fun-call",
                     "arrayfun: function requires at least 2 arguments");
      print_usage ();
      return retval;
    }

  octave_value func = args(0);
  bool symbol_table_lookup = false;

  if (func.is_string ())
    {
      // See if we can convert the string into a function.

      std::string name = args(0).string_value ();

      if (! valid_identifier (name))
        {
          std::string fcn_name = unique_symbol_name ("__arrayfun_fcn__");
          std::string fname = "function y = " + fcn_name + "(x) y = ";

          octave_function *ptr_func
            = extract_function (args(0), "arrayfun", fcn_name,
                                fname, "; endfunction");

          if (ptr_func && ! error_state)
            func = octave_value (ptr_func, true);
        }
      else
        {
          func = symbol_table::find_function (name);

          if (func.is_undefined ())
            error_with_id ("Octave:invalid-input-arg",
                           "arrayfun: invalid function NAME: %s",
                           name.c_str ());

          symbol_table_lookup = true;
        }

      if (error_state)
        return retval;
    }

  if (func.is_function_handle () || func.is_inline_function ()
      || func.is_function ())
    {
      // The following is an optimisation because the symbol table can
      // give a more specific function class, so this can result in
      // fewer polymorphic function calls as the function gets called
      // for each value of the array.

      if (! symbol_table_lookup)
        {
          if (func.is_function_handle ())
            {
              octave_fcn_handle* f = func.fcn_handle_value ();

              // Overloaded function handles need to check the type of
              // the arguments for each element of the array, so they
              // cannot be optimised this way.

              if (f -> is_overloaded ())
                goto nevermind;
            }
          octave_value f
            = symbol_table::find_function (func.function_value () -> name ());

          if (f.is_defined ())
            func = f;
        }

    nevermind:

      bool uniform_output = true;
      octave_value error_handler;

      get_mapper_fun_options (args, nargin, uniform_output, error_handler);

      if (error_state)
        return octave_value_list ();

      octave_value_list inputlist (nargin, octave_value ());

      OCTAVE_LOCAL_BUFFER (octave_value, inputs, nargin);
      OCTAVE_LOCAL_BUFFER (bool, mask, nargin);

      octave_idx_type k = 1;

      dim_vector fdims (1, 1);

      // Collect arguments.  Pre-fill scalar elements of inputlist
      // array.

      for (int j = 0; j < nargin; j++)
        {
          inputs[j] = args(j+1);
          mask[j] = inputs[j].numel () != 1;

          if (! mask[j])
            inputlist(j) = inputs[j];
        }

      for (int j = 0; j < nargin; j++)
        {
          if (mask[j])
            {
              fdims = inputs[j].dims ();
              k = inputs[j].numel ();

              for (int i = j+1; i < nargin; i++)
                {
                  if (mask[i] && inputs[i].dims () != fdims)
                    {
                      error_with_id ("Octave:invalid-input-arg",
                                     "arrayfun: dimensions mismatch");
                      return retval;
                    }
                }
              break;
            }
        }


      unwind_protect frame;
      frame.protect_var (buffer_error_messages);

      if (error_handler.is_defined ())
        buffer_error_messages++;

      // Apply functions.

      if (uniform_output)
        {
          std::list<octave_value_list> idx_list (1);
          idx_list.front ().resize (1);
          std::string idx_type = "(";

          OCTAVE_LOCAL_BUFFER (octave_value, retv, nargout1);

          for (octave_idx_type count = 0; count < k; count++)
            {
              idx_list.front ()(0) = count + 1.0;

              for (int j = 0; j < nargin; j++)
                {
                  if (mask[j])
                    inputlist.xelem (j) = inputs[j].do_index_op (idx_list);

                  if (error_state)
                    return retval;
                }

              const octave_value_list tmp
                = get_output_list (count, nargout, inputlist, func,
                                   error_handler);

              if (error_state)
                return retval;

              if (nargout > 0 && tmp.length () < nargout)
                {
                  error_with_id ("Octave:invalid-fun-call",
                                 "arrayfun: function returned fewer than nargout values");
                  return retval;
                }

              if  (nargout > 0
                   || (nargout == 0
                       && tmp.length () > 0 && tmp(0).is_defined ()))
                {
                  int num_to_copy = tmp.length ();

                  if (num_to_copy > nargout1)
                    num_to_copy = nargout1;

                  if (count == 0)
                    {
                      for (int j = 0; j < num_to_copy; j++)
                        {
                          if (tmp(j).is_defined ())
                            {
                              octave_value val = tmp(j);

                              if (val.numel () == 1)
                                retv[j] = val.resize (fdims);
                              else
                                {
                                  error_with_id ("Octave:invalid-fun-call",
                                                 "arrayfun: all values must be scalars when UniformOutput = true");
                                  break;
                                }
                            }
                        }
                    }
                  else
                    {
                      for (int j = 0; j < num_to_copy; j++)
                        {
                          if (tmp(j).is_defined ())
                            {
                              octave_value val = tmp(j);

                              if (! retv[j].fast_elem_insert (count, val))
                                {
                                  if (val.numel () == 1)
                                    {
                                      idx_list.front ()(0) = count + 1.0;
                                      retv[j].assign (octave_value::op_asn_eq,
                                                      idx_type, idx_list, val);

                                      if (error_state)
                                        break;
                                    }
                                  else
                                    {
                                      error_with_id ("Octave:invalid-fun-call",
                                                     "arrayfun: all values must be scalars when UniformOutput = true");
                                      break;
                                    }
                                }
                            }
                        }
                    }
                }

              if (error_state)
                break;
            }

          retval.resize (nargout1);

          for (int j = 0; j < nargout1; j++)
            {
              if (nargout > 0 && retv[j].is_undefined ())
                retval(j) = NDArray (fdims);
              else
                retval(j) = retv[j];
            }
        }
      else
        {
          std::list<octave_value_list> idx_list (1);
          idx_list.front ().resize (1);
          std::string idx_type = "(";

          OCTAVE_LOCAL_BUFFER (Cell, results, nargout1);

          for (int j = 0; j < nargout1; j++)
            results[j].resize (fdims, Matrix ());

          bool have_some_output = false;

          for (octave_idx_type count = 0; count < k; count++)
            {
              idx_list.front ()(0) = count + 1.0;

              for (int j = 0; j < nargin; j++)
                {
                  if (mask[j])
                    inputlist.xelem (j) = inputs[j].do_index_op (idx_list);

                  if (error_state)
                    return retval;
                }

              const octave_value_list tmp
                = get_output_list (count, nargout, inputlist, func,
                                   error_handler);

              if (error_state)
                return retval;

              if (nargout > 0 && tmp.length () < nargout)
                {
                  error_with_id ("Octave:invalid-fun-call",
                                 "arrayfun: function returned fewer than nargout values");
                  return retval;
                }

              if  (nargout > 0
                   || (nargout == 0
                       && tmp.length () > 0 && tmp(0).is_defined ()))
                {
                  int num_to_copy = tmp.length ();

                  if (num_to_copy > nargout1)
                    num_to_copy = nargout1;

                  if (num_to_copy > 0)
                    have_some_output = true;

                  for (int j = 0; j < num_to_copy; j++)
                    results[j](count) = tmp(j);
                }
            }

          if (have_some_output || fdims.any_zero ())
            {
              retval.resize (nargout1);

              for (int j = 0; j < nargout1; j++)
                retval(j) = results[j];
            }
        }
    }
  else
    error_with_id ("Octave:invalid-fun-call",
                   "arrayfun: argument NAME must be a string or function handle");

  return retval;
}

/*
%!function r = __f11 (x)
%!  global __arrayfun_test_num_outputs__;
%!  __arrayfun_test_num_outputs__ = nargout;
%!  r = x;
%!endfunction

%!function __f01 (x)
%!  global __arrayfun_test_num_outputs__;
%!  __arrayfun_test_num_outputs__ = nargout;
%!endfunction

%!test
%! global __arrayfun_test_num_outputs__;
%! arrayfun (@__f11, {1});
%! assert (__arrayfun_test_num_outputs__, 0);
%! x = arrayfun (@__f11, {1});
%! assert (__arrayfun_test_num_outputs__, 1);

%!test
%! global __arrayfun_test_num_outputs__;
%! arrayfun (@__f01, {1});
%! assert (__arrayfun_test_num_outputs__, 0);

%!error x = arrayfun (@__f01, [1, 2]);

%!test
%! assert (arrayfun (@__f11, [1, 2]), [1, 2]);
%! assert (arrayfun (@__f11, [1, 2], "uniformoutput", false), {1, 2});
%! assert (arrayfun (@__f11, {1, 2}), {1, 2});
%! assert (arrayfun (@__f11, {1, 2}, "uniformoutput", false), {{1}, {2}});

%!assert (arrayfun (@ones, 1, [2,3], "uniformoutput", false), {[1,1], [1,1,1]})

%% Test function to check the "Errorhandler" option
%!function z = __arrayfunerror (S, varargin)
%!  z = S;
%!endfunction
%% First input argument can be a string, an inline function, a
%% function_handle or an anonymous function
%!test
%! arrayfun (@isequal, [false, true], [true, true]); %% No output argument
%!error
%! arrayfun (@isequal); %% One or less input arguments
%!test
%! A = arrayfun ("isequal", [false, true], [true, true]);
%! assert (A, [false, true]);
%!test
%! A = arrayfun (inline ("(x == y)", "x", "y"), [false, true], [true, true]);
%! assert (A, [false, true]);
%!test
%! A = arrayfun (@isequal, [false, true], [true, true]);
%! assert (A, [false, true]);
%!test
%! A = arrayfun (@(x,y) isequal (x,y), [false, true], [true, true]);
%! assert (A, [false, true]);

%% Number of input and output arguments may be greater than one
%#!test
%! A = arrayfun (@(x) islogical (x), false);
%! assert (A, true);
%!test
%! A = arrayfun (@(x,y,z) x + y + z, [1, 1, 1], [2, 2, 2], [3, 4, 5]);
%! assert (A, [6, 7, 8], 1e-16);
%!test %% Two input arguments of different types
%! A = arrayfun (@(x,y) islogical (x) && ischar (y), false, "a");
%! assert (A, true);
%!test %% Pass another variable to the anonymous function
%! y = true;
%! A = arrayfun (@(x) islogical (x && y), false);
%! assert (A, true);
%!test %% Three ouptut arguments of different type
%! [A, B, C] = arrayfun (@find, [10, 11; 0, 12], "UniformOutput", false);
%! assert (isequal (A, {true, true; [], true}));
%! assert (isequal (B, {true, true; [], true}));
%! assert (isequal (C, {10, 11; [], 12}));

%% Input arguments can be of type logical
%!test
%! A = arrayfun (@(x,y) x == y, [false, true], [true, true]);
%! assert (A, [false, true]);
%!test
%! A = arrayfun (@(x,y) x == y, [false; true], [true; true], "UniformOutput", true);
%! assert (A, [false; true]);
%!test
%! A = arrayfun (@(x) x, [false, true, false, true], "UniformOutput", false);
%! assert (A, {false, true, false, true});
%!test %% Three ouptut arguments of same type
%! [A, B, C] = arrayfun (@find, [true, false; false, true], "UniformOutput", false);
%! assert (isequal (A, {true, []; [], true}));
%! assert (isequal (B, {true, []; [], true}));
%! assert (isequal (C, {true, []; [], true}));
%!test
%! A = arrayfun (@(x,y) array2str (x,y), true, true, ...
%!               "ErrorHandler", @__arrayfunerror);
%! assert (isfield (A, "identifier"), true);
%! assert (isfield (A, "message"), true);
%! assert (isfield (A, "index"), true);
%! assert (isempty (A.message), false);
%! assert (A.index, 1);
%!test %% Overwriting setting of "UniformOutput" true
%! A = arrayfun (@(x,y) array2str (x,y), true, true, "UniformOutput", true, ...
%!               "ErrorHandler", @__arrayfunerror);
%! assert (isfield (A, "identifier"), true);
%! assert (isfield (A, "message"), true);
%! assert (isfield (A, "index"), true);
%! assert (isempty (A.message), false);
%! assert (A.index, 1);

%% Input arguments can be of type numeric
%!test
%! A = arrayfun (@(x,y) x>y, [1.1, 4.2], [3.1, 2+3*i]);
%! assert (A, [false, true]);
%!test
%! A = arrayfun (@(x,y) x>y, [1.1, 4.2; 2, 4], [3.1, 2; 2, 4+2*i], "UniformOutput", true);
%! assert (A, [false, true; false, false]);
%!test
%! A = arrayfun (@(x,y) x:y, [1.1, 4], [3.1, 6], "UniformOutput", false);
%! assert (isequal (A{1}, [1.1, 2.1, 3.1]));
%! assert (isequal (A{2}, [4, 5, 6]));
%!test %% Three ouptut arguments of different type
%! [A, B, C] = arrayfun (@find, [10, 11; 0, 12], "UniformOutput", false);
%! assert (isequal (A, {true, true; [], true}));
%! assert (isequal (B, {true, true; [], true}));
%! assert (isequal (C, {10, 11; [], 12}));
%!test
%! A = arrayfun (@(x,y) array2str (x,y), {1.1, 4}, {3.1, 6}, ...
%!               "ErrorHandler", @__arrayfunerror);
%! B = isfield (A(1), "message") && isfield (A(1), "index");
%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
%! assert ([A(1).index, A(2).index], [1, 2]);
%!test %% Overwriting setting of "UniformOutput" true
%! A = arrayfun (@(x,y) array2str (x,y), {1.1, 4}, {3.1, 6}, ...
%!               "UniformOutput", true, "ErrorHandler", @__arrayfunerror);
%! B = isfield (A(1), "message") && isfield (A(1), "index");
%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
%! assert ([A(1).index, A(2).index], [1, 2]);

%% Input arguments can be of type character or strings
%!test
%! A = arrayfun (@(x,y) x>y, ["ad", "c", "ghi"], ["cc", "d", "fgh"]);
%! assert (A, [false, true, false, true, true, true]);
%!test
%! A = arrayfun (@(x,y) x>y, ["a"; "f"], ["c"; "d"], "UniformOutput", true);
%! assert (A, [false; true]);
%!test
%! A = arrayfun (@(x,y) x:y, ["a", "d"], ["c", "f"], "UniformOutput", false);
%! assert (A, {"abc", "def"});
%!test
%! A = arrayfun (@(x,y) cell2str (x,y), ["a", "d"], ["c", "f"], ...
%!               "ErrorHandler", @__arrayfunerror);
%! B = isfield (A(1), "identifier") && isfield (A(1), "message") && isfield (A(1), "index");
%! assert (B, true);

%% Input arguments can be of type structure
%!test
%! a = struct ("a", 1.1, "b", 4.2);  b = struct ("a", 3.1, "b", 2);
%! A = arrayfun (@(x,y) (x.a < y.a) && (x.b > y.b), a, b);
%! assert (A, true);
%!test
%! a = struct ("a", 1.1, "b", 4.2);  b = struct ("a", 3.1, "b", 2);
%! A = arrayfun (@(x,y) (x.a < y.a) && (x.b > y.b), a, b, "UniformOutput", true);
%! assert (A, true);
%!test
%! a = struct ("a", 1.1, "b", 4.2);  b = struct ("a", 3.1, "b", 2);
%! A = arrayfun (@(x,y) x.a:y.a, a, b, "UniformOutput", false);
%! assert (isequal (A, {[1.1, 2.1, 3.1]}));
%!test
%! A = arrayfun (@(x) mat2str(x), "a", "ErrorHandler", @__arrayfunerror);
%! assert (isfield (A, "identifier"), true);
%! assert (isfield (A, "message"), true);
%! assert (isfield (A, "index"), true);
%! assert (isempty (A.message), false);
%! assert (A.index, 1);
%!test %% Overwriting setting of "UniformOutput" true
%! A = arrayfun (@(x) mat2str(x), "a", "UniformOutput", true, ...
%!               "ErrorHandler", @__arrayfunerror);
%! assert (isfield (A, "identifier"), true);
%! assert (isfield (A, "message"), true);
%! assert (isfield (A, "index"), true);
%! assert (isempty (A.message), false);
%! assert (A.index, 1);

%% Input arguments can be of type cell array
%!test
%! A = arrayfun (@(x,y) x{1} < y{1}, {1.1, 4.2}, {3.1, 2});
%! assert (A, [true, false]);
%!test
%! A = arrayfun (@(x,y) x{1} < y{1}, {1.1; 4.2}, {3.1; 2}, "UniformOutput", true);
%! assert (A, [true; false]);
%!test
%! A = arrayfun (@(x,y) x{1} < y{1}, {1.1, 4.2}, {3.1, 2}, "UniformOutput", false);
%! assert (A, {true, false});
%!test
%! A = arrayfun (@(x,y) num2str(x,y), {1.1, 4.2}, {3.1, 2}, "ErrorHandler", @__arrayfunerror);
%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
%! assert ([A(1).index, A(2).index], [1, 2]);
%!test
%! A = arrayfun (@(x,y) num2str (x,y), {1.1, 4.2}, {3.1, 2}, ...
%!               "UniformOutput", true, "ErrorHandler", @__arrayfunerror);
%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
%! assert ([A(1).index, A(2).index], [1, 2]);
*/

static void
do_num2cell_helper (const dim_vector& dv,
                    const Array<int>& dimv,
                    dim_vector& celldv, dim_vector& arraydv,
                    Array<int>& perm)
{
  int dvl = dimv.length ();
  int maxd = dv.length ();
  celldv = dv;
  for (int i = 0; i < dvl; i++)
    maxd = std::max (maxd, dimv(i));
  if (maxd > dv.length ())
    celldv.resize (maxd, 1);
  arraydv = celldv;

  OCTAVE_LOCAL_BUFFER_INIT (bool, sing, maxd, false);

  perm.clear (maxd, 1);
  for (int i = 0; i < dvl; i++)
    {
      int k = dimv(i) - 1;
      if (k < 0)
        {
          error ("num2cell: dimension indices must be positive");
          return;
        }
      else if (i > 0 && k < dimv(i-1) - 1)
        {
          error ("num2cell: dimension indices must be strictly increasing");
          return;
        }

      sing[k] = true;
      perm(i) = k;
    }

  for (int k = 0, i = dvl; k < maxd; k++)
    if (! sing[k])
      perm(i++) = k;

  for (int i = 0; i < maxd; i++)
    if (sing[i])
      celldv(i) = 1;
    else
      arraydv(i) = 1;
}

template<class NDA>
static inline typename NDA::element_type
do_num2cell_elem (const NDA& array, octave_idx_type i)
{ return array(i); }

static inline Cell
do_num2cell_elem (const Cell& array, octave_idx_type i)
{ return Cell (array(i)); }


template<class NDA>
static Cell
do_num2cell (const NDA& array, const Array<int>& dimv)
{
  if (dimv.is_empty ())
    {
      Cell retval (array.dims ());
      octave_idx_type nel = array.numel ();
      for (octave_idx_type i = 0; i < nel; i++)
        retval.xelem (i) = do_num2cell_elem (array, i);

      return retval;
    }
  else
    {
      dim_vector celldv, arraydv;
      Array<int> perm;
      do_num2cell_helper (array.dims (), dimv, celldv, arraydv, perm);
      if (error_state)
        return Cell ();

      NDA parray = array.permute (perm);

      octave_idx_type nela = arraydv.numel ();
      octave_idx_type nelc = celldv.numel ();
      parray = parray.reshape (dim_vector (nela, nelc));

      Cell retval (celldv);
      for (octave_idx_type i = 0; i < nelc; i++)
        {
          retval.xelem (i) = NDA (parray.column (i).reshape (arraydv));
        }

      return retval;
    }
}

// FIXME: this is a mess, but if a size method for the object exists,
// we have to call it to get the size of the object instead of using the
// internal dims method.

static dim_vector
get_object_dims (octave_value& obj)
{
  dim_vector retval;

  Matrix m = obj.size ();

  int n = m.numel ();

  retval.resize (n);

  for (int i = 0; i < n; i++)
    retval(i) = m(i);

  return retval;
}

static Cell
do_object2cell (const octave_value& obj, const Array<int>& dimv)
{
  Cell retval;

  // FIXME: this copy is only needed because the octave_value::size
  // method is not const.
  octave_value array = obj;

  if (dimv.is_empty ())
    {
      dim_vector dv = get_object_dims (array);

      if (! error_state)
        {
          retval.resize (dv);

          octave_value_list idx (1);

          for (octave_idx_type i = 0; i < dv.numel (); i++)
            {
              octave_quit ();

              idx(0) = double (i+1);

              retval.xelem (i) = array.single_subsref ("(", idx);

              if (error_state)
                break;
            }
        }
    }
  else
    {
      error ("num2cell (A, dim) not implemented for class objects");
    }

  return retval;
}

DEFUN (num2cell, args, ,
       "-*- texinfo -*-\n\
@deftypefn  {Built-in Function} {@var{C} =} num2cell (@var{A})\n\
@deftypefnx {Built-in Function} {@var{C} =} num2cell (@var{A}, @var{dim})\n\
Convert the numeric matrix @var{A} to a cell array.\n\
\n\
If @var{dim} is defined, the value @var{C} is of dimension 1 in this\n\
dimension and the elements of @var{A} are placed into @var{C} in slices.\n\
For example:\n\
\n\
@example\n\
@group\n\
num2cell ([1,2;3,4])\n\
   @result{}\n\
      @{\n\
        [1,1] =  1\n\
        [2,1] =  3\n\
        [1,2] =  2\n\
        [2,2] =  4\n\
      @}\n\
num2cell ([1,2;3,4],1)\n\
   @result{}\n\
      @{\n\
        [1,1] =\n\
           1\n\
           3\n\
        [1,2] =\n\
           2\n\
           4\n\
      @}\n\
@end group\n\
@end example\n\
\n\
@seealso{mat2cell}\n\
@end deftypefn")
{
  int nargin =  args.length ();
  octave_value retval;

  if (nargin < 1 || nargin > 2)
    print_usage ();
  else
    {
      octave_value array = args(0);
      Array<int> dimv;
      if (nargin > 1)
        dimv = args(1).int_vector_value (true);

      if (error_state)
        ;
      else if (array.is_bool_type ())
        retval = do_num2cell (array.bool_array_value (), dimv);
      else if (array.is_char_matrix ())
        retval = do_num2cell (array.char_array_value (), dimv);
      else if (array.is_numeric_type ())
        {
          if (array.is_integer_type ())
            {
              if (array.is_int8_type ())
                retval = do_num2cell (array.int8_array_value (), dimv);
              else if (array.is_int16_type ())
                retval = do_num2cell (array.int16_array_value (), dimv);
              else if (array.is_int32_type ())
                retval = do_num2cell (array.int32_array_value (), dimv);
              else if (array.is_int64_type ())
                retval = do_num2cell (array.int64_array_value (), dimv);
              else if (array.is_uint8_type ())
                retval = do_num2cell (array.uint8_array_value (), dimv);
              else if (array.is_uint16_type ())
                retval = do_num2cell (array.uint16_array_value (), dimv);
              else if (array.is_uint32_type ())
                retval = do_num2cell (array.uint32_array_value (), dimv);
              else if (array.is_uint64_type ())
                retval = do_num2cell (array.uint64_array_value (), dimv);
            }
          else if (array.is_complex_type ())
            {
              if (array.is_single_type ())
                retval = do_num2cell (array.float_complex_array_value (), dimv);
              else
                retval = do_num2cell (array.complex_array_value (), dimv);
            }
          else
            {
              if (array.is_single_type ())
                retval = do_num2cell (array.float_array_value (), dimv);
              else
                retval = do_num2cell (array.array_value (), dimv);
            }
        }
      else if (array.is_object ())
        retval = do_object2cell (array, dimv);
      else if (array.is_map ())
        retval = do_num2cell (array.map_value (), dimv);
      else if (array.is_cell ())
        retval = do_num2cell (array.cell_value (), dimv);
      else if (array.is_object ())
        retval = do_num2cell (array.cell_value (), dimv);
      else
        gripe_wrong_type_arg ("num2cell", array);
    }

  return retval;
}

/*
%!assert (num2cell ([1,2;3,4]), {1,2;3,4})
%!assert (num2cell ([1,2;3,4], 1), {[1;3],[2;4]})
%!assert (num2cell ([1,2;3,4], 2), {[1,2];[3,4]})
*/

static bool
mat2cell_mismatch (const dim_vector& dv,
                   const Array<octave_idx_type> *d, int nd)
{
  for (int i = 0; i < nd; i++)
    {
      octave_idx_type s = 0;
      for (octave_idx_type j = 0; j < d[i].length (); j++)
        s += d[i](j);

      octave_idx_type r = i < dv.length () ? dv(i) : 1;

      if (s != r)
        {
          error ("mat2cell: mismatch on %d-th dimension (%d != %d)",
                 i+1, r, s);
          return true;
        }
    }

  return false;
}

template<class container>
static void
prepare_idx (container *idx, int idim, int nd,
             const Array<octave_idx_type>* d)
{
  octave_idx_type nidx = idim < nd ? d[idim].numel () : 1;
  if (nidx == 1)
    idx[0] = idx_vector::colon;
  else
    {
      octave_idx_type l = 0;
      for (octave_idx_type i = 0; i < nidx; i++)
        {
          octave_idx_type u = l + d[idim](i);
          idx[i] = idx_vector (l, u);
          l = u;
        }
    }
}

// 2D specialization, works for Array, Sparse and octave_map.
// Uses 1D or 2D indexing.

template <class Array2D>
static Cell
do_mat2cell_2d (const Array2D& a, const Array<octave_idx_type> *d, int nd)
{
  NoAlias<Cell> retval;
  assert (nd == 1 || nd == 2);
  assert (a.ndims () == 2);

  if (mat2cell_mismatch (a.dims (), d, nd))
    return retval;

  octave_idx_type nridx = d[0].length ();
  octave_idx_type ncidx = nd == 1 ? 1 : d[1].length ();
  retval.clear (nridx, ncidx);

  int ivec = -1;
  if (a.rows () > 1 && a.cols () == 1 && ncidx == 1)
    ivec = 0;
  else if (a.rows () == 1 && nridx == 1 && nd == 2)
    ivec = 1;

  if (ivec >= 0)
    {
      // Vector split. Use 1D indexing.
      octave_idx_type l = 0;
      octave_idx_type nidx = (ivec == 0 ? nridx : ncidx);
      for (octave_idx_type i = 0; i < nidx; i++)
        {
          octave_idx_type u = l + d[ivec](i);
          retval(i) = a.index (idx_vector (l, u));
          l = u;
        }
    }
  else
    {
      // General 2D case. Use 2D indexing.
      OCTAVE_LOCAL_BUFFER (idx_vector, ridx, nridx);
      prepare_idx (ridx, 0, nd, d);

      OCTAVE_LOCAL_BUFFER (idx_vector, cidx, ncidx);
      prepare_idx (cidx, 1, nd, d);

      for (octave_idx_type j = 0; j < ncidx; j++)
        for (octave_idx_type i = 0; i < nridx; i++)
          {
            octave_quit ();

            retval(i,j) = a.index (ridx[i], cidx[j]);
          }
    }

  return retval;
}

// Nd case. Works for Arrays and octave_map.
// Uses Nd indexing.

template <class ArrayND>
Cell
do_mat2cell_nd (const ArrayND& a, const Array<octave_idx_type> *d, int nd)
{
  NoAlias<Cell> retval;
  assert (nd >= 1);

  if (mat2cell_mismatch (a.dims (), d, nd))
    return retval;

  dim_vector rdv = dim_vector::alloc (nd);
  OCTAVE_LOCAL_BUFFER (octave_idx_type, nidx, nd);
  octave_idx_type idxtot = 0;
  for (int i = 0; i < nd; i++)
    {
      rdv(i) = nidx[i] = d[i].length ();
      idxtot += nidx[i];
    }

  retval.clear (rdv);

  OCTAVE_LOCAL_BUFFER (idx_vector, xidx, idxtot);
  OCTAVE_LOCAL_BUFFER (idx_vector *, idx, nd);

  idxtot = 0;
  for (int i = 0; i < nd; i++)
    {
      idx[i] = xidx + idxtot;
      prepare_idx (idx[i], i, nd, d);
      idxtot += nidx[i];
    }

  OCTAVE_LOCAL_BUFFER_INIT (octave_idx_type, ridx, nd, 0);
  NoAlias< Array<idx_vector> > ra_idx
    (dim_vector (1, std::max (nd, a.ndims ())), idx_vector::colon);

  for (octave_idx_type j = 0; j < retval.numel (); j++)
    {
      octave_quit ();

      for (int i = 0; i < nd; i++)
        ra_idx(i) = idx[i][ridx[i]];

      retval(j) = a.index (ra_idx);

      rdv.increment_index (ridx);
    }

  return retval;
}

// Dispatcher.
template <class ArrayND>
Cell
do_mat2cell (const ArrayND& a, const Array<octave_idx_type> *d, int nd)
{
  if (a.ndims () == 2 && nd <= 2)
    return do_mat2cell_2d (a, d, nd);
  else
    return do_mat2cell_nd (a, d, nd);
}

// General case. Works for any class supporting do_index_op.
// Uses Nd indexing.

Cell
do_mat2cell (octave_value& a, const Array<octave_idx_type> *d, int nd)
{
  NoAlias<Cell> retval;
  assert (nd >= 1);

  if (mat2cell_mismatch (a.dims (), d, nd))
    return retval;

  dim_vector rdv = dim_vector::alloc (nd);
  OCTAVE_LOCAL_BUFFER (octave_idx_type, nidx, nd);
  octave_idx_type idxtot = 0;
  for (int i = 0; i < nd; i++)
    {
      rdv(i) = nidx[i] = d[i].length ();
      idxtot += nidx[i];
    }

  retval.clear (rdv);

  OCTAVE_LOCAL_BUFFER (octave_value, xidx, idxtot);
  OCTAVE_LOCAL_BUFFER (octave_value *, idx, nd);

  idxtot = 0;
  for (int i = 0; i < nd; i++)
    {
      idx[i] = xidx + idxtot;
      prepare_idx (idx[i], i, nd, d);
      idxtot += nidx[i];
    }

  OCTAVE_LOCAL_BUFFER_INIT (octave_idx_type, ridx, nd, 0);
  octave_value_list ra_idx (std::max (nd, a.ndims ()),
                            octave_value::magic_colon_t);

  for (octave_idx_type j = 0; j < retval.numel (); j++)
    {
      octave_quit ();

      for (int i = 0; i < nd; i++)
        ra_idx(i) = idx[i][ridx[i]];

      retval(j) = a.do_index_op (ra_idx);

      if (error_state)
        break;

      rdv.increment_index (ridx);
    }

  return retval;
}

DEFUN (mat2cell, args, ,
       "-*- texinfo -*-\n\
@deftypefn  {Built-in Function} {@var{C} =} mat2cell (@var{A}, @var{m}, @var{n})\n\
@deftypefnx {Built-in Function} {@var{C} =} mat2cell (@var{A}, @var{d1}, @var{d2}, @dots{})\n\
@deftypefnx {Built-in Function} {@var{C} =} mat2cell (@var{A}, @var{r})\n\
Convert the matrix @var{A} to a cell array.\n\
\n\
If @var{A} is 2-D, then it is required that\n\
@code{sum (@var{m}) == size (@var{A}, 1)} and\n\
@code{sum (@var{n}) == size (@var{A}, 2)}.  Similarly, if @var{A} is\n\
multi-dimensional and the number of dimensional arguments is equal to the\n\
dimensions of @var{A}, then it is required that\n\
@code{sum (@var{di}) == size (@var{A}, i)}.\n\
\n\
Given a single dimensional argument @var{r}, the other dimensional\n\
arguments are assumed to equal @code{size (@var{A},@var{i})}.\n\
\n\
An example of the use of mat2cell is\n\
\n\
@example\n\
mat2cell (reshape (1:16,4,4), [3,1], [3,1])\n\
@result{}\n\
@{\n\
   [1,1] =\n\
\n\
      1   5   9\n\
      2   6  10\n\
      3   7  11\n\
\n\
   [2,1] =\n\
\n\
      4   8  12\n\
\n\
   [1,2] =\n\
\n\
     13\n\
     14\n\
     15\n\
\n\
   [2,2] = 16\n\
@}\n\
@end example\n\
@seealso{num2cell, cell2mat}\n\
@end deftypefn")
{
  int nargin = args.length ();
  octave_value retval;

  if (nargin < 2)
    print_usage ();
  else
    {
      // Prepare indices.
      OCTAVE_LOCAL_BUFFER (Array<octave_idx_type>, d, nargin-1);

      for (int i = 1; i < nargin; i++)
        {
          d[i-1] = args(i).octave_idx_type_vector_value (true);
          if (error_state)
            return retval;
        }

      octave_value a = args(0);
      bool sparse = a.is_sparse_type ();
      if (sparse && nargin > 3)
        {
          error ("mat2cell: sparse arguments only support 2-D indexing");
          return retval;
        }

      switch (a.builtin_type ())
        {
        case btyp_double:
          {
            if (sparse)
              retval = do_mat2cell_2d (a.sparse_matrix_value (), d, nargin-1);
            else
              retval = do_mat2cell (a.array_value (), d, nargin - 1);
            break;
          }
        case btyp_complex:
          {
            if (sparse)
              retval = do_mat2cell_2d (a.sparse_complex_matrix_value (), d,
                                       nargin-1);
            else
              retval = do_mat2cell (a.complex_array_value (), d, nargin - 1);
            break;
          }
#define BTYP_BRANCH(X,Y) \
        case btyp_ ## X: \
            retval = do_mat2cell (a.Y ## _value (), d, nargin - 1); \
          break

        BTYP_BRANCH (float, float_array);
        BTYP_BRANCH (float_complex, float_complex_array);
        BTYP_BRANCH (bool, bool_array);
        BTYP_BRANCH (char, char_array);

        BTYP_BRANCH (int8,  int8_array);
        BTYP_BRANCH (int16, int16_array);
        BTYP_BRANCH (int32, int32_array);
        BTYP_BRANCH (int64, int64_array);
        BTYP_BRANCH (uint8,  uint8_array);
        BTYP_BRANCH (uint16, uint16_array);
        BTYP_BRANCH (uint32, uint32_array);
        BTYP_BRANCH (uint64, uint64_array);

        BTYP_BRANCH (cell, cell);
        BTYP_BRANCH (struct, map);
#undef BTYP_BRANCH

        case btyp_func_handle:
          gripe_wrong_type_arg ("mat2cell", a);
          break;
        default:
          retval = do_mat2cell (a, d, nargin-1);
        }
    }

  return retval;
}

/*
%!test
%! x = reshape (1:20, 5, 4);
%! c = mat2cell (x, [3,2], [3,1]);
%! assert (c, {[1,6,11;2,7,12;3,8,13],[16;17;18];[4,9,14;5,10,15],[19;20]});

%!test
%! x = "abcdefghij";
%! c = mat2cell (x, 1, [0,4,2,0,4,0]);
%! empty1by0str = resize ("", 1, 0);
%! assert (c, {empty1by0str,"abcd","ef",empty1by0str,"ghij",empty1by0str});
*/

// FIXME: it would be nice to allow ranges being handled without a conversion.
template <class NDA>
static Cell
do_cellslices_nda (const NDA& array,
                   const Array<octave_idx_type>& lb,
                   const Array<octave_idx_type>& ub,
                   int dim = -1)
{
  octave_idx_type n = lb.length ();
  Cell retval (1, n);
  if (array.is_vector () && (dim == -1
                             || (dim == 0 && array.columns () == 1)
                             || (dim == 1 && array.rows () == 1)))
    {
      for (octave_idx_type i = 0; i < n && ! error_state; i++)
        retval(i) = array.index (idx_vector (lb(i) - 1, ub(i)));
    }
  else
    {
      const dim_vector dv = array.dims ();
      int ndims = dv.length ();
      if (dim < 0)
        dim = dv.first_non_singleton ();
      ndims = std::max (ndims, dim + 1);

      Array<idx_vector> idx (dim_vector (ndims, 1), idx_vector::colon);

      for (octave_idx_type i = 0; i < n && ! error_state; i++)
        {
          idx(dim) = idx_vector (lb(i) - 1, ub(i));
          retval(i) = array.index (idx);
        }
    }

  return retval;
}

DEFUN (cellslices, args, ,
       "-*- texinfo -*-\n\
@deftypefn {Built-in Function} {@var{sl} =} cellslices (@var{x}, @var{lb}, @var{ub}, @var{dim})\n\
Given an array @var{x}, this function produces a cell array of slices from\n\
the array determined by the index vectors @var{lb}, @var{ub}, for lower and\n\
upper bounds, respectively.\n\
\n\
In other words, it is equivalent to the following code:\n\
\n\
@example\n\
@group\n\
n = length (lb);\n\
sl = cell (1, n);\n\
for i = 1:length (lb)\n\
  sl@{i@} = x(:,@dots{},lb(i):ub(i),@dots{},:);\n\
endfor\n\
@end group\n\
@end example\n\
\n\
The position of the index is determined by @var{dim}.  If not specified,\n\
slicing is done along the first non-singleton dimension.\n\
@seealso{cell2mat, cellindexmat, cellfun}\n\
@end deftypefn")
{
  octave_value retval;
  int nargin = args.length ();
  if (nargin == 3 || nargin == 4)
    {
      octave_value x = args(0);
      Array<octave_idx_type> lb = args(1).octave_idx_type_vector_value ();
      Array<octave_idx_type> ub = args(2).octave_idx_type_vector_value ();
      int dim = -1;
      if (nargin == 4)
        {
          dim = args(3).int_value () - 1;
          if (dim < 0)
            error ("cellslices: DIM must be a valid dimension");
        }

      if (! error_state)
        {
          if (lb.length () != ub.length ())
            error ("cellslices: the lengths of LB and UB must match");
          else
            {
              Cell retcell;
              if (! x.is_sparse_type () && x.is_matrix_type ())
                {
                  // specialize for some dense arrays.
                  if (x.is_bool_type ())
                    retcell = do_cellslices_nda (x.bool_array_value (),
                                                 lb, ub, dim);
                  else if (x.is_char_matrix ())
                    retcell = do_cellslices_nda (x.char_array_value (),
                                                 lb, ub, dim);
                  else if (x.is_integer_type ())
                    {
                      if (x.is_int8_type ())
                        retcell = do_cellslices_nda (x.int8_array_value (),
                                                     lb, ub, dim);
                      else if (x.is_int16_type ())
                        retcell = do_cellslices_nda (x.int16_array_value (),
                                                     lb, ub, dim);
                      else if (x.is_int32_type ())
                        retcell = do_cellslices_nda (x.int32_array_value (),
                                                     lb, ub, dim);
                      else if (x.is_int64_type ())
                        retcell = do_cellslices_nda (x.int64_array_value (),
                                                     lb, ub, dim);
                      else if (x.is_uint8_type ())
                        retcell = do_cellslices_nda (x.uint8_array_value (),
                                                     lb, ub, dim);
                      else if (x.is_uint16_type ())
                        retcell = do_cellslices_nda (x.uint16_array_value (),
                                                     lb, ub, dim);
                      else if (x.is_uint32_type ())
                        retcell = do_cellslices_nda (x.uint32_array_value (),
                                                     lb, ub, dim);
                      else if (x.is_uint64_type ())
                        retcell = do_cellslices_nda (x.uint64_array_value (),
                                                     lb, ub, dim);
                    }
                  else if (x.is_complex_type ())
                    {
                      if (x.is_single_type ())
                        retcell = do_cellslices_nda (x.float_complex_array_value (),
                                                     lb, ub, dim);
                      else
                        retcell = do_cellslices_nda (x.complex_array_value (),
                                                     lb, ub, dim);
                    }
                  else
                    {
                      if (x.is_single_type ())
                        retcell = do_cellslices_nda (x.float_array_value (),
                                                     lb, ub, dim);
                      else
                        retcell = do_cellslices_nda (x.array_value (),
                                                     lb, ub, dim);
                    }
                }
              else
                {
                  // generic code.
                  octave_idx_type n = lb.length ();
                  retcell = Cell (1, n);
                  const dim_vector dv = x.dims ();
                  int ndims = dv.length ();
                  if (dim < 0)
                    dim = dv.first_non_singleton ();
                  ndims = std::max (ndims, dim + 1);
                  octave_value_list idx (ndims, octave_value::magic_colon_t);
                  for (octave_idx_type i = 0; i < n && ! error_state; i++)
                    {
                      idx(dim) = Range (lb(i), ub(i));
                      retcell(i) = x.do_index_op (idx);
                    }
                }
              if (! error_state)
                retval = retcell;
            }
        }
    }
  else
    print_usage ();

  return retval;
}

/*
%!test
%! m = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12];
%! c = cellslices (m, [1, 2], [2, 3], 2);
%! assert (c, {[1, 2; 5, 6; 9, 10], [2, 3; 6, 7; 10, 11]});
*/

DEFUN (cellindexmat, args, ,
       "-*- texinfo -*-\n\
@deftypefn {Built-in Function} {@var{y} =} cellindexmat (@var{x}, @var{varargin})\n\
Perform indexing of matrices in a cell array.\n\
\n\
Given a cell array of matrices @var{x}, this function computes\n\
\n\
@example\n\
@group\n\
Y = cell (size (X));\n\
for i = 1:numel (X)\n\
  Y@{i@} = X@{i@}(varargin@{:@});\n\
endfor\n\
@end group\n\
@end example\n\
@seealso{cellslices, cellfun}\n\
@end deftypefn")
{
  octave_value retval;
  if (args.length () >= 1)
    {
      if (args(0).is_cell ())
        {
          const Cell x = args(0).cell_value ();
          NoAlias<Cell> y(x.dims ());
          octave_idx_type nel = x.numel ();
          octave_value_list idx = args.slice (1, args.length () - 1);

          for (octave_idx_type i = 0; i < nel; i++)
            {
              octave_quit ();
              octave_value tmp = x(i);
              y(i) = tmp.do_index_op (idx);
              if (error_state)
                break;
            }

          retval = y;
        }
      else
        error ("cellindexmat: X must be a cell");
    }
  else
    print_usage ();

  return retval;
}