{"id":2158,"date":"2017-01-19T10:19:14","date_gmt":"2017-01-19T15:19:14","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=2158"},"modified":"2017-01-05T10:21:11","modified_gmt":"2017-01-05T15:21:11","slug":"vectorizing-graphics-operations","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2017\/01\/19\/vectorizing-graphics-operations\/","title":{"rendered":"Vectorizing Graphics Operations"},"content":{"rendered":"<div class=\"content\"><!--introduction--><p>Let's talk about changing characteristics of elements in a plot today.  I will use an example derived from one in <a href=\"https:\/\/www.mathworks.com\/products\/mapping.html\">Mapping Toolbox<\/a>. My goal is to show you good ways to modify your graphics.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#092270e4-990f-4af7-8f74-df0e7865972d\">Set Up<\/a><\/li><li><a href=\"#17136f59-5386-46a0-89d3-9ba0c0937b8a\">Read the USA high resolution data<\/a><\/li><li><a href=\"#82af2204-6f55-41e4-ab81-96fba388b0bf\">Create Base Map<\/a><\/li><li><a href=\"#d43f0add-96db-4522-8622-94257d49fd8d\">Change One State Color<\/a><\/li><li><a href=\"#e2c8e58d-6f49-4c61-b9f0-529bce1975d1\">Change Another One<\/a><\/li><li><a href=\"#193548e2-7468-450b-b7f1-4cf916c0d7d0\">Set All States' Patches to One Color<\/a><\/li><li><a href=\"#b3e4266f-2201-4242-8c4d-590be18474da\">Change Each State to a Different Color - for loop<\/a><\/li><li><a href=\"#14323f60-e253-4849-b3b6-77ddf432cb12\">Change Each State to a Different Color - set<\/a><\/li><li><a href=\"#f6657ce6-492f-460f-ad7d-70448f431102\">Conclusion<\/a><\/li><\/ul><\/div><h4>Set Up<a name=\"092270e4-990f-4af7-8f74-df0e7865972d\"><\/a><\/h4><p>First I put the examples directory onto my path so I can get the shape file containing state borders as polygons.<\/p><pre class=\"codeinput\">addpath(fullfile(userpath, <span class=\"string\">'Examples'<\/span>,<span class=\"string\">'mapexgeo'<\/span>))\r\n<\/pre><h4>Read the USA high resolution data<a name=\"17136f59-5386-46a0-89d3-9ba0c0937b8a\"><\/a><\/h4><pre class=\"codeinput\">states = shaperead(<span class=\"string\">'usastatehi'<\/span>,<span class=\"string\">'UseGeoCoords'<\/span>,true);\r\n<\/pre><p><a href=\"https:\/\/www.mathworks.com\/help\/map\/ref\/makesymbolspec.html\">Create a SymbolSpec<\/a> to display Alaska and Hawaii as red polygons.<\/p><pre class=\"codeinput\">symbols = makesymbolspec(<span class=\"string\">'Polygon'<\/span>, <span class=\"keyword\">...<\/span>\r\n    {<span class=\"string\">'Name'<\/span>,<span class=\"string\">'Alaska'<\/span>,<span class=\"string\">'FaceColor'<\/span>,<span class=\"string\">'red'<\/span>}, <span class=\"keyword\">...<\/span>\r\n    {<span class=\"string\">'Name'<\/span>,<span class=\"string\">'Hawaii'<\/span>,<span class=\"string\">'FaceColor'<\/span>,<span class=\"string\">'red'<\/span>});\r\n<\/pre><h4>Create Base Map<a name=\"82af2204-6f55-41e4-ab81-96fba388b0bf\"><\/a><\/h4><p>Create a worldmap of North America with Alaska and Hawaii in red, all other states in blue.<\/p><pre class=\"codeinput\">figure\r\nworldmap(<span class=\"string\">'north america'<\/span>)\r\nstatePatches = geoshow(states,<span class=\"string\">'SymbolSpec'<\/span>,symbols, <span class=\"keyword\">...<\/span>\r\n    <span class=\"string\">'DefaultFaceColor'<\/span>,<span class=\"string\">'blue'<\/span>,<span class=\"string\">'DefaultEdgeColor'<\/span>,<span class=\"string\">'black'<\/span>)\r\naxis <span class=\"string\">off<\/span>\r\n<\/pre><pre class=\"codeoutput\">statePatches = \r\n  Group with properties:\r\n\r\n    Children: [51&times;1 Patch]\r\n     Visible: 'on'\r\n     HitTest: 'on'\r\n\r\n  Use GET to show all properties\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2017\/vecHG2_01.png\" alt=\"\"> <h4>Change One State Color<a name=\"d43f0add-96db-4522-8622-94257d49fd8d\"><\/a><\/h4><p>We can change the color of one state using the easy dot-notation.  And a different way to find out about the states.<\/p><pre class=\"codeinput\">statePatches.Children(17).FaceColor = <span class=\"string\">'y'<\/span>;\r\nstates(17).Name\r\n<\/pre><pre class=\"codeoutput\">ans =\r\nKentucky\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2017\/vecHG2_02.png\" alt=\"\"> <h4>Change Another One<a name=\"e2c8e58d-6f49-4c61-b9f0-529bce1975d1\"><\/a><\/h4><p>And I can change a state color to a custom one instead.<\/p><pre class=\"codeinput\">statePatches.Children(42).FaceColor = [0.2, 0.8, 0.7];\r\nstates(42).Name\r\n<\/pre><pre class=\"codeoutput\">ans =\r\nTennessee\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2017\/vecHG2_03.png\" alt=\"\"> <h4>Set All States' Patches to One Color<a name=\"193548e2-7468-450b-b7f1-4cf916c0d7d0\"><\/a><\/h4><p>Now change all the states' colors to magenta.  In this case, I have to assemble all of the patches together, into a <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/comma-separated-lists.html\">comma-separated list<\/a> for the left-hand side.  And I need to make sure I have as many outputs from the right-hand side, hence the use of <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/deal.html\"><tt>deal<\/tt><\/a>.<\/p><pre class=\"codeinput\">[statePatches.Children.FaceColor] = deal(<span class=\"string\">'m'<\/span>);\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2017\/vecHG2_04.png\" alt=\"\"> <p>Now change each state to different colors.  Let's make an array of colors first.<\/p><pre class=\"codeinput\">stateColors1 = rand(length(states),3);\r\nstateColors2 = fliplr(stateColors1);\r\n<\/pre><h4>Change Each State to a Different Color - for loop<a name=\"b3e4266f-2201-4242-8c4d-590be18474da\"><\/a><\/h4><p>We can do this with a loop, of course.  Even though this is a relatively small example, let's time it for fun.<\/p><pre class=\"codeinput\">tic\r\n<span class=\"keyword\">for<\/span> npatch = 1:length(states)\r\n    statePatches.Children(npatch).FaceColor = stateColors1(npatch,:);\r\n<span class=\"keyword\">end<\/span>\r\ncolorTimes = toc;\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2017\/vecHG2_05.png\" alt=\"\"> <p>We can also do this in a vectorized way, which can provide a huge time savings if there are enough patches involved.  In this case, with 51 patches, time is not really a big issue.  We have seen customers improve the speed of their code tremendously with scenes that are much more complicated.<\/p><p>What we need to do is not set each color separately.  Instead we use the \"old-fashioned\" function <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/set.html\"><tt>set<\/tt><\/a>, and take advantage of the vectorization it offers. What I have to do is pass in an array of handles.  Also, I enclose the property (or properties) I want to adjust in a cell array. And I supply the inputs for each handle as elements of a matching cell array.  This requires that I convert my triplets for RGB into cells.  And I can do that readily with <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/num2cell.html\"><tt>num2cell<\/tt><\/a>.<\/p><h4>Change Each State to a Different Color - set<a name=\"14323f60-e253-4849-b3b6-77ddf432cb12\"><\/a><\/h4><p>Here we go.<\/p><pre class=\"codeinput\">tic\r\nset(statePatches.Children, {<span class=\"string\">'FaceColor'<\/span>}, num2cell(flipud(stateColors2),2));\r\ncolorTimes(2) = toc\r\n<\/pre><pre class=\"codeoutput\">colorTimes =\r\n     0.052154     0.026216\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2017\/vecHG2_06.png\" alt=\"\"> <h4>Conclusion<a name=\"f6657ce6-492f-460f-ad7d-70448f431102\"><\/a><\/h4><p>Sometimes vectorization for graphics happens with no major effort.  Like changing every patch to a single color. Using the notation introduced with the updated graphics system is easy and your code is highly readable.<\/p><p>Sometimes for performance, there may be instances where vectorizing is still appropriate, and you can't get it with the new notation.  In that case, you will need the various techniques and functions I used in this post. Will this be helpful to you?  Please share your thoughts on this <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=2158#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_3ef834c4332640d5977ac7b0cfa45262() {\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='3ef834c4332640d5977ac7b0cfa45262 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 3ef834c4332640d5977ac7b0cfa45262';\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 2017 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_3ef834c4332640d5977ac7b0cfa45262()\"><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; R2016b<br><\/p><\/div><!--\r\n3ef834c4332640d5977ac7b0cfa45262 ##### SOURCE BEGIN #####\r\n%% Vectorizing Graphics Operations\r\n% Let's talk about changing characteristics of elements in a plot today.  I\r\n% will use an example derived from one in\r\n% <https:\/\/www.mathworks.com\/products\/mapping.html Mapping Toolbox>.\r\n% My goal is to show you good ways to modify your graphics.\r\n%% Set Up\r\n% First I put the examples directory onto my path so I can get the shape\r\n% file containing state borders as polygons.\r\naddpath(fullfile(userpath, 'Examples','mapexgeo'))\r\n\r\n%% Read the USA high resolution data\r\nstates = shaperead('usastatehi','UseGeoCoords',true);\r\n\r\n%%\r\n% <https:\/\/www.mathworks.com\/help\/map\/ref\/makesymbolspec.html Create a\r\n% SymbolSpec> to display Alaska and Hawaii as red polygons.\r\nsymbols = makesymbolspec('Polygon', ...\r\n    {'Name','Alaska','FaceColor','red'}, ...\r\n    {'Name','Hawaii','FaceColor','red'});\r\n\r\n%% Create Base Map\r\n% Create a worldmap of North America with Alaska and Hawaii in red, \r\n% all other states in blue.\r\nfigure\r\nworldmap('north america')\r\nstatePatches = geoshow(states,'SymbolSpec',symbols, ...\r\n    'DefaultFaceColor','blue','DefaultEdgeColor','black')\r\naxis off\r\n\r\n%% Change One State Color\r\n% We can change the color of one state using the easy dot-notation.  And a\r\n% different way to find out about the states.\r\nstatePatches.Children(17).FaceColor = 'y';\r\nstates(17).Name\r\n\r\n%% Change Another One\r\n% And I can change a state color to a custom one instead.\r\nstatePatches.Children(42).FaceColor = [0.2, 0.8, 0.7];\r\nstates(42).Name\r\n\r\n%% Set All States' Patches to One Color\r\n% Now change all the states' colors to magenta.  In this case, I have to\r\n% assemble all of the patches together, into a\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/comma-separated-lists.html\r\n% comma-separated list> for the left-hand side.  And I need to make sure I\r\n% have as many outputs from the right-hand side, hence the use of\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/deal.html |deal|>.\r\n[statePatches.Children.FaceColor] = deal('m');\r\n\r\n%% \r\n% Now change each state to different colors.  Let's make an array of colors\r\n% first.\r\nstateColors1 = rand(length(states),3);\r\nstateColors2 = fliplr(stateColors1);\r\n\r\n%% Change Each State to a Different Color - for loop\r\n% We can do this with a loop, of course.  Even though this is a relatively\r\n% small example, let's time it for fun.\r\ntic\r\nfor npatch = 1:length(states)\r\n    statePatches.Children(npatch).FaceColor = stateColors1(npatch,:);\r\nend\r\ncolorTimes = toc;\r\n\r\n%%\r\n% We can also do this in a vectorized way, which can provide a huge time\r\n% savings if there are enough patches involved.  In this case, with 51\r\n% patches, time is not really a big issue.  We have seen customers improve\r\n% the speed of their code tremendously with scenes that are much more\r\n% complicated.\r\n%\r\n% What we need to do is not set each color separately.  Instead we use the\r\n% \"old-fashioned\" function\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/set.html |set|>, and take\r\n% advantage of the vectorization it offers. What I have to do is pass in an\r\n% array of handles.  Also, I enclose the property (or properties) I want to\r\n% adjust in a cell array. And I supply the inputs for each handle as\r\n% elements of a matching cell array.  This requires that I convert my\r\n% triplets for RGB into cells.  And I can do that readily with \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/num2cell.html |num2cell|>.\r\n%% Change Each State to a Different Color - set\r\n% Here we go.\r\ntic\r\nset(statePatches.Children, {'FaceColor'}, num2cell(flipud(stateColors2),2));\r\ncolorTimes(2) = toc\r\n%% Conclusion\r\n% Sometimes vectorization for graphics happens with no major effort.  Like\r\n% changing every patch to a single color. Using the notation introduced\r\n% with the updated graphics system is easy and your code is highly\r\n% readable. \r\n%\r\n% Sometimes for performance, there may be instances where vectorizing is\r\n% still appropriate, and you can't get it with the new notation.  In that\r\n% case, you will need the various techniques and functions I used in this\r\n% post. Will this be helpful to you?  Please share your thoughts on this\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=2158#respond here>.\r\n\r\n##### SOURCE END ##### 3ef834c4332640d5977ac7b0cfa45262\r\n-->","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2017\/vecHG2_06.png\" onError=\"this.style.display ='none';\" \/><\/div><!--introduction--><p>Let's talk about changing characteristics of elements in a plot today.  I will use an example derived from one in <a href=\"https:\/\/www.mathworks.com\/products\/mapping.html\">Mapping Toolbox<\/a>. My goal is to show you good ways to modify your graphics.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2017\/01\/19\/vectorizing-graphics-operations\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/2158"}],"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=2158"}],"version-history":[{"count":3,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/2158\/revisions"}],"predecessor-version":[{"id":2161,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/2158\/revisions\/2161"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=2158"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=2158"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=2158"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}