diff structArray.m @ 817:b723495cdb2f v0.2

Add functions for easily creating struct arrays and struct cell arrays
author Jonatan Werpers <jonatan@werpers.com>
date Fri, 07 Sep 2018 09:21:57 +0200
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/structArray.m	Fri Sep 07 09:21:57 2018 +0200
@@ -0,0 +1,16 @@
+% % Usage example:
+% c = structArray({'a','b'}, {
+%     1, 2;
+%     3, 4;
+% });
+
+function c = structArray(fields, values)
+    assert(length(fields) == size(values, 2), 'Number of fields and number of colums of ''values'' must be equal');
+    c = struct();
+
+    for i = 1:size(values, 1)
+        for j = 1:length(fields)
+            c(i).(fields{j}) = values{i,j};
+        end
+    end
+end