help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Changeset} Re: cellfunc vs cell2mat speed?


From: John W. Eaton
Subject: [Changeset} Re: cellfunc vs cell2mat speed?
Date: Thu, 11 Sep 2008 17:04:22 -0400

On 10-Sep-2008, David Bateman wrote:

| I'd suggest something like teh attached changeset that improves the 
| speed but keeps teh code compatible.

Thanks, I applied it along with the additional change you sent
off the list.  The combined change is attached below as a single
changeset.

jwe

# HG changeset patch
# User David Bateman <address@hidden>
# Date 1221167006 14400
# Node ID 3b2346046d32ad8a819b26236c575a6fc2a1436a
# Parent  c066714ee5d53d68fe5db9c69f2e47b8edfaab14
improve speed of cell2mat

diff --git a/scripts/ChangeLog b/scripts/ChangeLog
--- a/scripts/ChangeLog
+++ b/scripts/ChangeLog
@@ -1,3 +1,7 @@
+2008-09-11  David Bateman  <address@hidden>
+
+       * general/cell2mat.m: Improve the speed.
+
 2008-09-09  John W. Eaton  <address@hidden>
 
        * time/datestr.m: Convert format and use strftime to do most of
diff --git a/scripts/general/cell2mat.m b/scripts/general/cell2mat.m
--- a/scripts/general/cell2mat.m
+++ b/scripts/general/cell2mat.m
@@ -48,20 +48,46 @@
     else
       error ("cell2mat: all elements of cell array must be numeric, logical or 
char");
     endif
+  elseif (ndims (c) == 2)
+    nr = rows (c);
+    c1 = cell (nr, 1);
+    for i = 1 : nr
+      c1{i} = [c{i : nr : end}];
+    endfor
+    ## This is faster than "c = cat(1, c{:})"
+    m = [cellfun(@(x) x.', c1, "UniformOutput", false){:}].';
   else
-    ## n dimensions case
-    for k = ndims (c):-1:2,
+   nd = ndims (c);
+   for k = nd : -1 : 2
       sz = size (c);
+      if (k > ndims (c) || sz(end) == 1)
+       continue;
+      endif
       sz(end) = 1;
       c1 = cell (sz);
-      for i = 1:(prod (sz))
-        c1{i} = cat (k, c{i:(prod (sz)):end});
-      endfor
+      sz = prod (sz);
+      if (k == 2)
+        for i = 1 : sz
+         c1{i} = [c{i : sz : end}];
+        endfor
+      else
+        ## This is faster than
+        ##   for i = 1:sz, c1{i} = cat (k, c{i:(prod (sz)):end}); endfor
+       idx = [1, k, (3 : (k - 1)), 2, ((k + 1): nd)];
+        c = cellfun(@(x) permute (x, idx), c, "UniformOutput", false);
+        for i = 1: sz
+         c1{i} = ipermute ([c{i : sz : end}], idx);
+        endfor
+      endif
       c = c1;
     endfor
-    m = cat (1, c1{:});
+    if (numel (c) > 1)
+      idx = [2, 1, 3 : nd];
+      m = ipermute([cellfun(@(x) permute (x, idx), c, "UniformOutput", 
false){:}], idx);
+    else
+      m = c{1};
+    endif
   endif
-
 endfunction
 
 ## Tests

reply via email to

[Prev in Thread] Current Thread [Next in Thread]