{"id":67,"date":"2006-11-24T10:25:05","date_gmt":"2006-11-24T15:25:05","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=67"},"modified":"2007-03-08T09:43:14","modified_gmt":"2007-03-08T14:43:14","slug":"working-with-arrays-of-structures","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2006\/11\/24\/working-with-arrays-of-structures\/","title":{"rendered":"Working with Arrays of Structures"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>Though I have covered this topic somewhat in the past, it seems like a good time to refresh the information.  There are recent\r\n         posts on the MATLAB newsgroup relating to this topic such as <a href=\"\">this one<\/a>.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Original Question<\/a><\/li>\r\n         <li><a href=\"#5\">Alternatives<\/a><\/li>\r\n         <li><a href=\"#8\">Solution<\/a><\/li>\r\n         <li><a href=\"#12\">Related Topics<\/a><\/li>\r\n         <li><a href=\"#13\">Your Thoughts<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Original Question<a name=\"1\"><\/a><\/h3>\r\n   <p>Suppose I have a structure array and want to find all the entries with a value of 4, <b>without looping<\/b>, something like <tt>[m,n] = find(f.h == 4)<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">f(1).h = [1 2 3 4];\r\nf(2).h = [5 6 7 8];\r\n<span style=\"color: #0000FF\">try<\/span>\r\n [m,n] = find(f.h == 4);\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><p>Why can't I use the <tt>find<\/tt> statement directly?  Let's take a look at the error message to understand.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">lerr = lasterror;\r\ndisp(lerr.message)<\/pre><pre style=\"font-style:oblique\">Error using ==&gt; eq\r\nToo many input arguments.\r\n<\/pre><p>Too many input arguments?  What <b>is<\/b> <tt>f.h<\/tt>? For that matter, what exactly is <tt>f<\/tt> again?\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">f<\/pre><pre style=\"font-style:oblique\">f = \r\n1x2 struct array with fields:\r\n    h\r\n<\/pre><p><tt>f<\/tt> is a <tt>struct<\/tt> array, and <tt>f.h<\/tt> is a comma-separated list.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">f.h<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1     2     3     4\r\nans =\r\n     5     6     7     8\r\n<\/pre><h3>Alternatives<a name=\"5\"><\/a><\/h3>\r\n   <p>To turn this list into a MATLAB construct I can use, I'd normally either wrap it inside <tt>[]<\/tt> or <tt>{}<\/tt>.  If I wrap <tt>f.h<\/tt> inside <tt>[]<\/tt>, I lose the information about what is in the first element of <tt>f<\/tt> and what is in the second.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">[f.h]<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1     2     3     4     5     6     7     8\r\n<\/pre><p>Wrapping <tt>f.h<\/tt> inside <tt>{}<\/tt>, I have a cell array to work with.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">{f.h}<\/pre><pre style=\"font-style:oblique\">ans = \r\n    [1x4 double]    [1x4 double]\r\n<\/pre><p>I still can't immediately use <tt>find<\/tt> or numeric functions on this array.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">try<\/span>\r\n    [m,n] = find({f.h} == 4);\r\n<span style=\"color: #0000FF\">end<\/span>\r\nlerr = lasterror;\r\ndisp(lerr.message)<\/pre><pre style=\"font-style:oblique\">Error using ==&gt; evalin\r\nUndefined function or method 'eq' for input arguments of type 'cell'.\r\n<\/pre><h3>Solution<a name=\"8\"><\/a><\/h3>\r\n   <p>What I'd like is a way to work with my struct, without writing too much code, without looping, that is ideally a pattern I\r\n      can reuse as my problem evolves.  This is exactly what <tt>arrayfun<\/tt> was designed to help with.  It works on each element of an array, and I need to just tell it what I want to operate on one\r\n      element, as well as telling <tt>arrayfun<\/tt> what array to work on.\r\n   <\/p>\r\n   <p>Let's first find the values in the struct array <tt>f<\/tt> equal to 4.  Since I have 2 arrays embedded in <tt>f<\/tt>, and they may each have different numbers of outputs, I have to clearly state that the outputs need to go into a cell array.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">[m,n] = arrayfun(@(x)find(x.h==4),f,<span style=\"color: #A020F0\">'uniformoutput'<\/span>,false)<\/pre><pre style=\"font-style:oblique\">m = \r\n    [1]    [1x0 double]\r\nn = \r\n    [4]    [1x0 double]\r\n<\/pre><p>This becomes even more obvious if I can another array, <tt>g<\/tt> that is even less \"regular\" than <tt>f<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">g = f;\r\ng(3).h = [1 2 17 4];\r\ng(4).h = [1 3 17 5 9 17];\r\n[mg,ng] = arrayfun(@(x)find(x.h==17),g,<span style=\"color: #A020F0\">'uniformoutput'<\/span>,false)<\/pre><pre style=\"font-style:oblique\">mg = \r\n    [1x0 double]    [1x0 double]    [1]    [1x2 double]\r\nng = \r\n    [1x0 double]    [1x0 double]    [3]    [1x2 double]\r\n<\/pre><p>Some problems are more benign however and it would be wasteful to return results in a cell array and then have to unpack them\r\n      into a numeric array, for example, the function <tt>max<\/tt>, which generally has a single value as the result.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">[minval,idx] = arrayfun(@(x)max(x.h),f)\r\n[minval,idx] = arrayfun(@(x)max(x.h),g)<\/pre><pre style=\"font-style:oblique\">minval =\r\n     4     8\r\nidx =\r\n     4     4\r\nminval =\r\n     4     8    17    17\r\nidx =\r\n     4     4     3     3\r\n<\/pre><h3>Related Topics<a name=\"12\"><\/a><\/h3>\r\n   <p>Here are some links to related blogs and MATLAB reference pages.<\/p>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=42\">Cell Arrays and Their Contents<\/a><\/li>\r\n         <li><a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=39\">Structures and Comma-Separated Lists<\/a><\/li>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/company\/newsletters\/articles\/new-functions-for-vectorizing-operations-on-any-data-type.html\">New Functions for Vectorizing Operations on Any Data Type<\/a><\/li>\r\n         <li><a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/arrayfun.html\"><tt>arrayfun<\/tt><\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Your Thoughts<a name=\"13\"><\/a><\/h3>\r\n   <div>\r\n      <ul>\r\n         <li>Do you use struct arrays?<\/li>\r\n         <li>If yes, do you use <tt>arrayfun<\/tt>, or do you use loops?  Whichever your choice is, can you say more about why it's your choice?\r\n         <\/li>\r\n         <li>Do you avoid struct arrays all together and use something else? If so, what data representations do you use instead?<\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>Let's see your feedback <a href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/11\/24\/working-with-arrays-of-structures\/#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\"> \r\n<!--\r\n    function grabCode_b65267e9e5d149559dd27c1a77e70f97() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='b65267e9e5d149559dd27c1a77e70f97 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' b65267e9e5d149559dd27c1a77e70f97';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Loren Shure';\r\n        copyright = 'Copyright 2006 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      } \r\n-->  \r\n      <\/script>\r\n<noscript>\r\n<em>A Javascript-enabled browser is required to use the \"Get the MATLAB code\" link.<\/em>\r\n<\/noscript>\r\n<p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_b65267e9e5d149559dd27c1a77e70f97()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code<\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.3<br><\/p>\r\n<\/div>\r\n<!--\r\nb65267e9e5d149559dd27c1a77e70f97 ##### SOURCE BEGIN #####\r\n%% Working with Arrays of Structures\r\n% Though I have covered this topic somewhat in the past, it seems like a\r\n% good time to refresh the information.  There are\r\n% recent posts on the MATLAB newsgroup relating to this topic\r\n% such as < this one>.\r\n\r\n%% Original Question\r\n% Suppose I have a structure array and want to find all the entries\r\n% with a value of 4, *without looping*, something like \r\n% |[m,n] = find(f.h == 4)|.\r\n\r\nf(1).h = [1 2 3 4];\r\nf(2).h = [5 6 7 8];\r\ntry\r\n [m,n] = find(f.h == 4);\r\nend\r\n\r\n%%\r\n% Why can't I use the |find| statement directly?  Let's take a look at the\r\n% error message to understand.\r\nlerr = lasterror;\r\ndisp(lerr.message)\r\n\r\n%%\r\n% Too many input arguments?  What *is* |f.h|? For that matter, what exactly\r\n% is |f| again?\r\nf\r\n\r\n%%\r\n% |f| is a |struct| array, and |f.h| is a comma-separated list.\r\nf.h\r\n\r\n%% Alternatives\r\n% To turn this list into a MATLAB construct I can use, I'd\r\n% normally either wrap it inside |[]| or |{}|.  If I wrap |f.h| inside\r\n% |[]|, I lose the information about what is in the first element of |f| and\r\n% what is in the second.\r\n[f.h]\r\n\r\n%%\r\n% Wrapping |f.h| inside |{}|, I have a cell array to work with.\r\n{f.h}\r\n\r\n%%\r\n% I still can't immediately use |find| or numeric functions on this array.\r\ntry\r\n    [m,n] = find({f.h} == 4);\r\nend\r\nlerr = lasterror;\r\ndisp(lerr.message)\r\n\r\n%% Solution\r\n% What I'd like is a way to work with my struct, without writing too much\r\n% code, without looping, that is ideally a pattern I can reuse as my\r\n% problem evolves.  This is exactly what |arrayfun| was designed to help\r\n% with.  It works on each element of an array, and I need to just tell it\r\n% what I want to operate on one element, as well as telling |arrayfun| what\r\n% array to work on.\r\n%%\r\n% Let's first find the values in the struct array |f| equal to 4.  Since I\r\n% have 2 arrays embedded in |f|, and they may each have different numbers\r\n% of outputs, I have to clearly state that the outputs need to go into a\r\n% cell array.\r\n[m,n] = arrayfun(@(x)find(x.h==4),f,'uniformoutput',false)\r\n%%\r\n% This becomes even more obvious if I can another array, |g| that is even\r\n% less \"regular\" than |f|.\r\ng = f;\r\ng(3).h = [1 2 17 4];\r\ng(4).h = [1 3 17 5 9 17];\r\n[mg,ng] = arrayfun(@(x)find(x.h==17),g,'uniformoutput',false)\r\n\r\n%%\r\n% Some problems are more benign however and it would be wasteful to return\r\n% results in a cell array and then have to unpack them into a numeric\r\n% array, for example, the function |max|, which generally has a single\r\n% value as the result.\r\n[minval,idx] = arrayfun(@(x)max(x.h),f)\r\n[minval,idx] = arrayfun(@(x)max(x.h),g)\r\n\r\n%% Related Topics\r\n% Here are some links to related blogs and MATLAB reference pages.\r\n%\r\n% * <https:\/\/blogs.mathworks.com\/loren\/?p=42 Cell Arrays and Their Contents>\r\n% * <https:\/\/blogs.mathworks.com\/loren\/?p=39 Structures and Comma-Separated Lists>\r\n% * <https:\/\/www.mathworks.com\/company\/newsletters\/articles\/new-functions-for-vectorizing-operations-on-any-data-type.html New Functions for Vectorizing Operations on Any Data Type>\r\n% * <https:\/\/www.mathworks.com\/help\/matlab\/ref\/arrayfun.html |arrayfun|>\r\n%\r\n\r\n%% Your Thoughts\r\n%\r\n% * Do you use struct arrays?\r\n% * If yes, do you use |arrayfun|, or do you use loops?  Whichever your\r\n% choice is, can you say more about why it's your choice?\r\n% * Do you avoid struct arrays all together and use something else? If so,\r\n% what data representations do you use instead?\r\n%\r\n% Let's see your feedback <?p=67#respond here>.\r\n##### SOURCE END ##### b65267e9e5d149559dd27c1a77e70f97\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Though I have covered this topic somewhat in the past, it seems like a good time to refresh the information.  There are recent\r\n         posts on the MATLAB newsgroup relating to this... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/11\/24\/working-with-arrays-of-structures\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[5],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/67"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=67"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/67\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=67"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=67"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=67"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}