{"id":2033,"date":"2016-09-26T08:57:34","date_gmt":"2016-09-26T13:57:34","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=2033"},"modified":"2016-09-30T23:47:39","modified_gmt":"2016-10-01T04:47:39","slug":"indexing-with-curly-braces","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2016\/09\/26\/indexing-with-curly-braces\/","title":{"rendered":"Indexing with Curly Braces"},"content":{"rendered":"<div class=\"content\"><!--introduction--><p>I have talked about indexing a bunch of times <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/indexing\/?s_tid=Blog_loren_Category\">in the past<\/a>, including my last post.  Recently I have visited quite a few customers who still get tripped up a bit sometimes.  So I thought I'd try again.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#a101a6ed-dc78-469f-8288-01572b81b3ad\">Cell Arrays<\/a><\/li><li><a href=\"#662e37c1-7823-45d6-b17b-7d177913e0a2\">Where People Trip<\/a><\/li><li><a href=\"#36dfa1c7-bb3f-4ef6-8c84-0035fbd3e54e\">How to Extract Contents from a Cell<\/a><\/li><li><a href=\"#4a172b8d-9860-44f1-9de4-16798f918237\">What If I Want the Contents from Multiple Cells?<\/a><\/li><li><a href=\"#2f6e0237-f505-452a-aaca-d2487c40ab54\">Tables<\/a><\/li><li><a href=\"#562d99e4-565e-4555-a7bc-bf97b553756f\">Extra the Data Compatible with Numbers<\/a><\/li><li><a href=\"#06c760cb-2a09-4d39-b8c8-48be4a1e8c5c\">Follow Up<\/a><\/li><\/ul><\/div><h4>Cell Arrays<a name=\"a101a6ed-dc78-469f-8288-01572b81b3ad\"><\/a><\/h4><p>What are cell arrays?  In MATLAB, they are variables that hold, in each \"cell\", other MATLAB variables. And they are \"regular\".  By that, I mean that they have a uniform layout, equal numbers of elements in each row, each column, each page, etc. as you march along the dimensions.  How do you get information into them, and out from them?<\/p><h4>Where People Trip<a name=\"662e37c1-7823-45d6-b17b-7d177913e0a2\"><\/a><\/h4><p>One of the common places I see people trip is accessing information from <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/cell.html\">cell arrays<\/a>.<\/p><h4>How to Extract Contents from a Cell<a name=\"36dfa1c7-bb3f-4ef6-8c84-0035fbd3e54e\"><\/a><\/h4><p>There are lots of ways to get information into a cell array, but the most widely used, I suspect, is via {} (curly braces).<\/p><pre class=\"codeinput\">myCell = {<span class=\"string\">'Loren'<\/span>, 17, <span class=\"string\">'summer'<\/span>, <span class=\"string\">'travel'<\/span>, magic(5), true}\r\n<\/pre><pre class=\"codeoutput\">myCell = \r\n    'Loren'    [17]    'summer'    'travel'    [5x5 double]    [1]\r\n<\/pre><p>You might remember from my previous post that if I index into the cell array using smooth parentheses, I extract the selected portion of the origin array.<\/p><p>So how do I extract the contents? You extract contents from a cell using curly brace indexing.<\/p><pre class=\"codeinput\">firstCell = myCell{1}\r\nsecondCell = myCell{2}\r\n<\/pre><pre class=\"codeoutput\">firstCell =\r\nLoren\r\nsecondCell =\r\n    17\r\n<\/pre><h4>What If I Want the Contents from Multiple Cells?<a name=\"4a172b8d-9860-44f1-9de4-16798f918237\"><\/a><\/h4><p>In that case, the cells that I want need to be capable of concatenation in MATLAB, unless I extract them each separately.  Anything else is likely to cause an error (hedging my language here since I have not thought exhaustively about this wording).<\/p><pre class=\"codeinput\">myCell2 = {17, 45, 33, 78; 10 20 30 40}\r\nmyCell2small = myCell2([1 2],1:3) <span class=\"comment\">% a cell array as well<\/span>\r\ncontentsAsOneArray = [myCell2{[1 2], 3}]\r\n<\/pre><pre class=\"codeoutput\">myCell2 = \r\n    [17]    [45]    [33]    [78]\r\n    [10]    [20]    [30]    [40]\r\nmyCell2small = \r\n    [17]    [45]    [33]\r\n    [10]    [20]    [30]\r\ncontentsAsOneArray =\r\n    33    30\r\n<\/pre><p>To see what I mean about capable of being concatenated, check this out.<\/p><pre class=\"codeinput\"><span class=\"keyword\">try<\/span>\r\n    myCell3 = [myCell{[1,6]}]\r\n<span class=\"keyword\">catch<\/span> myError\r\n    disp(myError.message)\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><pre class=\"codeoutput\">The following error occurred converting from logical to char:\r\nConversion to char from logical is not possible.\r\n<\/pre><p>Since it is not possible to concatenate logical and character arrays, we can't extract the 2 elements into one element of a new variable.<\/p><p>But I can collect compatible items, as long as their dimensions are consistent.  So I can't combine cells 2 and 5 from <tt>myCell<\/tt>.<\/p><pre class=\"codeinput\"><span class=\"keyword\">try<\/span>\r\n    myCell4 = [myCell{[2,5]}]\r\n<span class=\"keyword\">catch<\/span> myError\r\n    disp(myError.message)\r\n<span class=\"keyword\">end<\/span>\r\n<\/pre><pre class=\"codeoutput\">Dimensions of matrices being concatenated are not consistent.\r\n<\/pre><p>But I can combine the strings from cells 1 and 3 since they are both row vectors of characters.<\/p><pre class=\"codeinput\">myCell5 = [myCell{[1,3]}]\r\n<\/pre><pre class=\"codeoutput\">myCell5 =\r\nLorensummer\r\n<\/pre><h4>Tables<a name=\"2f6e0237-f505-452a-aaca-d2487c40ab54\"><\/a><\/h4><p>You can do very similar things with tables in terms of indexing as you can with cell arrays.  As I did last time, I'm going to load in data from a MAT-file, into a <tt>struct<\/tt> rather than into separate variables.<\/p><pre class=\"codeinput\">Structpatient = load(<span class=\"string\">'patients.mat'<\/span>);\r\n<\/pre><p>Next convert it to a <tt>table<\/tt>.<\/p><pre class=\"codeinput\">Tpatient = struct2table(Structpatient);\r\n<\/pre><p>And let's create a smaller table from this so we can see the details more easily without being overwhelmed.<\/p><pre class=\"codeinput\">Tmine = Tpatient(1:5, [1 2 5 6 8 end])\r\n<\/pre><pre class=\"codeoutput\">Tmine = \r\n     Gender      LastName     Smoker    Systolic    Height    SelfAssessedHealthStatus\r\n    ________    __________    ______    ________    ______    ________________________\r\n    'Male'      'Smith'       true      124         71        'Excellent'             \r\n    'Male'      'Johnson'     false     109         69        'Fair'                  \r\n    'Female'    'Williams'    false     125         64        'Good'                  \r\n    'Female'    'Jones'       false     117         67        'Fair'                  \r\n    'Female'    'Brown'       false     122         64        'Good'                  \r\n<\/pre><h4>Extra the Data Compatible with Numbers<a name=\"562d99e4-565e-4555-a7bc-bf97b553756f\"><\/a><\/h4><p>To get the data out from columns 3 through 5, I index in a similar way to extracting cell array information.<\/p><pre class=\"codeinput\">myNumValues = Tmine{:,3:5}\r\n<\/pre><pre class=\"codeoutput\">myNumValues =\r\n     1   124    71\r\n     0   109    69\r\n     0   125    64\r\n     0   117    67\r\n     0   122    64\r\n<\/pre><p>One of the many nice properties of using tables is that the data you extract from them is not \"flattened\" into a row vector as it is when you do from a cell array.  Compare the previous statement to this one for the cell array <tt>myCell2<\/tt>.<\/p><pre class=\"codeinput\">myNumValuesFrommyCell2 = [myCell2{:,:}]\r\n<\/pre><pre class=\"codeoutput\">myNumValuesFrommyCell2 =\r\n    17    10    45    20    33    30    78    40\r\n<\/pre><h4>Follow Up<a name=\"06c760cb-2a09-4d39-b8c8-48be4a1e8c5c\"><\/a><\/h4><p>I hope you find this helpful.  Please see some of the earlier posts on indexing to understand more about cell arrays and <a title=\"https:\/\/www.mathworks.com\/help\/releases\/R2016a\/matlab\/matlab_prog\/comma-separated-lists.html (link no longer works)\">comma-separated lists<\/a>. You can let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=2033#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_5f8838f35e1e495293d8a7ddb4dcf68c() {\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='5f8838f35e1e495293d8a7ddb4dcf68c ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 5f8838f35e1e495293d8a7ddb4dcf68c';\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        copyright = 'Copyright 2016 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 copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\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     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_5f8838f35e1e495293d8a7ddb4dcf68c()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2016a<br><\/p><\/div><!--\r\n5f8838f35e1e495293d8a7ddb4dcf68c ##### SOURCE BEGIN #####\r\n%% Indexing with Curly Braces\r\n% I have talked about indexing a bunch of times\r\n% <https:\/\/blogs.mathworks.com\/loren\/category\/indexing\/?s_tid=Blog_loren_Category\r\n% in the past>, including my last post.  Recently I have visited quite a\r\n% few customers who still get tripped up a bit sometimes.  So I thought I'd\r\n% try again.\r\n%\r\n%% Cell Arrays\r\n% What are cell arrays?  In MATLAB, they are variables that hold, in each\r\n% \"cell\", other MATLAB variables. And they are \"regular\".  By that, I mean\r\n% that they have a uniform layout, equal numbers of elements in each row,\r\n% each column, each page, etc. as you march along the dimensions.  How do\r\n% you get information into them, and out from them?\r\n%% Where People Trip\r\n% One of the common places I see people trip is accessing information from\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/cell.html cell arrays>.\r\n%% How to Extract Contents from a Cell\r\n% There are lots of ways to get information into a cell array, but the most\r\n% widely used, I suspect, is via {} (curly braces).  \r\nmyCell = {'Loren', 17, 'summer', 'travel', magic(5), true}\r\n%%\r\n% You might remember from my previous post that if I index into the cell\r\n% array using smooth parentheses, I extract the selected portion of the\r\n% origin array.\r\n%\r\n% So how do I extract the contents? You extract contents from a cell\r\n% using curly brace indexing.\r\nfirstCell = myCell{1}\r\nsecondCell = myCell{2}\r\n%% What If I Want the Contents from Multiple Cells?\r\n% In that case, the cells that I want need to be capable of concatenation\r\n% in MATLAB, unless I extract them each separately.  Anything else\r\n% is likely to cause an error (hedging my language here since I have not\r\n% thought exhaustively about this wording).\r\nmyCell2 = {17, 45, 33, 78; 10 20 30 40}\r\nmyCell2small = myCell2([1 2],1:3) % a cell array as well\r\ncontentsAsOneArray = [myCell2{[1 2], 3}]\r\n%%\r\n% To see what I mean about capable of being concatenated, check this out.\r\ntry\r\n    myCell3 = [myCell{[1,6]}]\r\ncatch myError\r\n    disp(myError.message)\r\nend\r\n\r\n%%\r\n% Since it is not possible to concatenate logical and character arrays, we\r\n% can't extract the 2 elements into one element of a new variable.\r\n%\r\n% But I can collect compatible items, as long as their dimensions are\r\n% consistent.  So I can't combine cells 2 and 5 from |myCell|.\r\n\r\ntry\r\n    myCell4 = [myCell{[2,5]}]\r\ncatch myError\r\n    disp(myError.message)\r\nend\r\n\r\n%%\r\n% But I can combine the strings from cells 1 and 3 since they are both\r\n% row vectors of characters.\r\nmyCell5 = [myCell{[1,3]}]\r\n\r\n%% Tables\r\n% You can do very similar things with tables in terms of indexing as you\r\n% can with cell arrays.  As I did last time, I'm going to load in data from\r\n% a MAT-file, into a |struct| rather than into separate variables.\r\nStructpatient = load('patients.mat');\r\n%%\r\n% Next convert it to a |table|.\r\nTpatient = struct2table(Structpatient);\r\n%%\r\n% And let's create a smaller table from this so we can see the details more\r\n% easily without being overwhelmed.\r\nTmine = Tpatient(1:5, [1 2 5 6 8 end])\r\n\r\n%% Extra the Data Compatible with Numbers\r\n% To get the data out from columns 3 through 5, I index in a similar way to\r\n% extracting cell array information.\r\n\r\nmyNumValues = Tmine{:,3:5}\r\n\r\n%%\r\n% One of the many nice properties of using tables is that the data you\r\n% extract from them is not \"flattened\" into a row vector as it is when you\r\n% do from a cell array.  Compare the previous statement to this one for the\r\n% cell array |myCell2|.\r\n\r\nmyNumValuesFrommyCell2 = [myCell2{:,:}]\r\n\r\n%% Follow Up\r\n% I hope you find this helpful.  Please see some of the earlier posts on\r\n% indexing to understand more about cell arrays and\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2016a\/matlab\/matlab_prog\/comma-separated-lists.html\r\n% comma-separated lists>. You can let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=2033#respond here>.\r\n##### SOURCE END ##### 5f8838f35e1e495293d8a7ddb4dcf68c\r\n-->","protected":false},"excerpt":{"rendered":"<!--introduction--><p>I have talked about indexing a bunch of times <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/indexing\/?s_tid=Blog_loren_Category\">in the past<\/a>, including my last post.  Recently I have visited quite a few customers who still get tripped up a bit sometimes.  So I thought I'd try again.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2016\/09\/26\/indexing-with-curly-braces\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[4],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/2033"}],"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=2033"}],"version-history":[{"count":3,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/2033\/revisions"}],"predecessor-version":[{"id":2061,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/2033\/revisions\/2061"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=2033"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=2033"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=2033"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}