{"id":138,"date":"2008-05-14T15:06:36","date_gmt":"2008-05-14T20:06:36","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2008\/05\/14\/acting-on-specific-elements\/"},"modified":"2008-05-14T15:38:08","modified_gmt":"2008-05-14T20:38:08","slug":"acting-on-specific-elements","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2008\/05\/14\/acting-on-specific-elements\/","title":{"rendered":"Acting on Specific Elements in a Matrix"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>Using MATLAB, there are several ways to identify elements from an array for which you wish to perform some action. Depending\r\n         on how you've chosen the elements, you may either have the list of elements to toss or the list if elements to retain.  And\r\n         you might not have much if any control yourself how the list gets presented to you since the list could be passed to you from\r\n         another calculation.  The lists might be indices, subscripts, or logical arrays (often referred to as masks). Let's look at\r\n         how you might arrive at such a situation and see what the code looks like to perform one particular action, setting the desired\r\n         element values to 0.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#2\">General Setup<\/a><\/li>\r\n         <li><a href=\"#4\">Method #1 - Using Subscripts of Keepers<\/a><\/li>\r\n         <li><a href=\"#12\">Method #2 - Using Indices of Keepers<\/a><\/li>\r\n         <li><a href=\"#13\">Method #3 - Using Logical Keepers<\/a><\/li>\r\n         <li><a href=\"#15\">Method #4 - Subscripts for Elements to Set to Zero<\/a><\/li>\r\n         <li><a href=\"#18\">Method #5 - Indices for Elements to Set to Zero<\/a><\/li>\r\n         <li><a href=\"#19\">Method #6 - Using Logical Arrays to Specify Zero Elements<\/a><\/li>\r\n         <li><a href=\"#20\">Which Method(s) Do You Prefer?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>Note: I am not discussing efficiency in this article.  It is highly dependent on the number of elements in the original array\r\n      and how many will be retained or thrown out.  This article focuses on specifying what to keep or replace.\r\n   <\/p>\r\n   <h3>General Setup<a name=\"2\"><\/a><\/h3>\r\n   <p>Here's the setup for this investigation.  I will use a fixed matrix for all the methods and always end up with the same final\r\n      output.  The plan is to show you multiple ways to get the result, since different methods may be appropriate under different\r\n      circumstances.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A = magic(17);\r\nResult = A;\r\nResult( A &lt; mean(A(:)) ) = 0;<\/pre><p>Let's look at the nonzero pattern of <tt>Result<\/tt> using <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/spy.html\"><tt>spy<\/tt><\/a>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">spy(Result)<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/138\/removeElements_01.png\"> <h3>Method #1 - Using Subscripts of Keepers<a name=\"4\"><\/a><\/h3>\r\n   <p>Here's a list of the subscripts for the elements to keep unchanged.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">[rA,cA] = find(A &gt; (17^2)\/2);<\/pre><p>Next we convert the subscripts to indices.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">Result1 = zeros(size(A));\r\nindices = sub2ind(size(A),rA,cA);\r\nResult1(indices) = A(indices);\r\nisequal(Result, Result1)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1\r\n<\/pre><p>Why did I convert subscripts to indices?  Let me illustrate with a very small example.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">matrix = [ -1 1 0; 2 0 -2; 0 3 -3]\r\n[rows,cols] = find(matrix==0)<\/pre><pre style=\"font-style:oblique\">matrix =\r\n    -1     1     0\r\n     2     0    -2\r\n     0     3    -3\r\nrows =\r\n     3\r\n     2\r\n     1\r\ncols =\r\n     1\r\n     2\r\n     3\r\n<\/pre><p>Now let's see what I get if I use the subscripts to address the selected elements:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">matrix(rows,cols)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     0     3    -3\r\n     2     0    -2\r\n    -1     1     0\r\n<\/pre><p>I get the full matrix back, even though I selected only 3 elements. This definitely surprised me when I first encountered\r\n      this.  What's happening?\r\n   <\/p>\r\n   <p>MATLAB matches each row element with each column element. <tt>matrix([1 2 3],2)<\/tt> returns the elements from rows 1 through 3 in column 1.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">matrix(1:3,2)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1\r\n     0\r\n     3\r\n<\/pre><p>To learn more about indexing in general, you might want to read <a href=\"https:\/\/blogs.mathworks.com\/loren\/?s=essence\">these posts<\/a> or search the MATLAB documentation.\r\n   <\/p>\r\n   <h3>Method #2 - Using Indices of Keepers<a name=\"12\"><\/a><\/h3>\r\n   <p>Here we used the single output form of <tt>find<\/tt> which returns indices instead of subscripts.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">indA = find(A &gt; (17^2)\/2);\r\nResult2 = zeros(size(A));\r\nResult2(indA) = A(indA);\r\nisequal(Result, Result2)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1\r\n<\/pre><h3>Method #3 - Using Logical Keepers<a name=\"13\"><\/a><\/h3>\r\n   <p>We'll try keeping about half of the elements unchanged.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">keepA = (A &gt; (17^2)\/2);\r\nResult3 = zeros(size(A));\r\nResult3(keepA) = A(keepA);\r\nisequal(Result, Result3)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1\r\n<\/pre><p><tt>keepA<\/tt> is a <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/logical.html\"><tt>logical<\/tt><\/a> matrix the same size as <tt>A<\/tt>.  I use logical indexing to populate <tt>Result3<\/tt> with the chosen values from <tt>A<\/tt>.\r\n   <\/p>\r\n   <h3>Method #4 - Subscripts for Elements to Set to Zero<a name=\"15\"><\/a><\/h3>\r\n   <p>If instead we have a list of candidates to set to 0, we have an easier time since we don't need to start off with a matrix\r\n      of <tt>zeros<\/tt>.  Instead we start with a copy of <tt>A<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">Result4 = A;\r\n[rnotA,cnotA] = find(A &lt;= (17^2)\/2);<\/pre><p>Convert indices to subscripts, as in method #1.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">indices = sub2ind(size(A),rnotA,cnotA);<\/pre><p>Now zero out the selected matrix elements.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">Result4(indices) = 0;\r\nisequal(Result, Result4)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1\r\n<\/pre><h3>Method #5 - Indices for Elements to Set to Zero<a name=\"18\"><\/a><\/h3>\r\n   <p>If we're instead given indices, we simply skip the step of converting subscripts and follow similar logic to that in method\r\n      #4.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">Result5 = A;\r\nindnotA = find(A &lt;= (17^2)\/2);\r\nResult5(indnotA) = 0;\r\nisequal(Result, Result5)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1\r\n<\/pre><h3>Method #6 - Using Logical Arrays to Specify Zero Elements<a name=\"19\"><\/a><\/h3>\r\n   <p>Finally, if we have a mask for the values to set to 0, we simply use it to select and set elements.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">Result6 = A;\r\nkeepnotA = (A &lt;= (17^2)\/2);\r\nResult6(keepnotA) = 0;\r\nisequal(Result, Result6)<\/pre><pre style=\"font-style:oblique\">ans =\r\n     1\r\n<\/pre><h3>Which Method(s) Do You Prefer?<a name=\"20\"><\/a><\/h3>\r\n   <p>Which method or methods do you naturally find yourself using?  Do you ever invert the logic of your algorithm to fit your\r\n      way of thinking about addressing the data (the ins or the outs)?  Please post your thoughts <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=138#respond\">here<\/a>.  I look forward to seeing them.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_73889325f9414369b5488daea331b0f1() {\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='73889325f9414369b5488daea331b0f1 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 73889325f9414369b5488daea331b0f1';\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 2008 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-->\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_73889325f9414369b5488daea331b0f1()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.6<br><\/p>\r\n<\/div>\r\n<!--\r\n73889325f9414369b5488daea331b0f1 ##### SOURCE BEGIN #####\r\n%% Acting on Specific Elements in a Matrix\r\n% Using MATLAB, there are several ways to identify elements from an array\r\n% for which you wish to perform some action.\r\n% Depending on how you've chosen the elements, you may either have the list\r\n% of elements to toss or the list if elements to retain.  And you might not\r\n% have much if any control yourself how the list gets presented to you\r\n% since the list could be passed to you from another calculation.  The\r\n% lists might be indices, subscripts, or logical arrays (often referred to\r\n% as masks). Let's look at how you might arrive at such a situation and see\r\n% what the code looks like to perform one particular action, setting the\r\n% desired element values to 0.\r\n%%\r\n% Note: I am not discussing efficiency in this article.  It is highly\r\n% dependent on the number of elements in the original array and how many\r\n% will be retained or thrown out.  This article focuses on specifying what\r\n% to keep or replace.\r\n%% General Setup\r\n% Here's the setup for this investigation.  I will use a fixed matrix for\r\n% all the methods and always end up with the same final output.  The plan\r\n% is to show you multiple ways to get the result, since different methods\r\n% may be appropriate under different circumstances.  \r\nA = magic(17);\r\nResult = A;\r\nResult( A < mean(A(:)) ) = 0;\r\n%% \r\n% Let's look at the nonzero pattern of |Result| using <https:\/\/www.mathworks.com\/help\/matlab\/ref\/spy.html |spy|>.\r\nspy(Result)\r\n%% Method #1 - Using Subscripts of Keepers\r\n% Here's a list of the subscripts for the elements to keep unchanged.\r\n[rA,cA] = find(A > (17^2)\/2);\r\n%%\r\n% Next we convert the subscripts to indices. \r\n%%\r\nResult1 = zeros(size(A));\r\nindices = sub2ind(size(A),rA,cA);\r\nResult1(indices) = A(indices);\r\nisequal(Result, Result1)\r\n%%\r\n% Why did I convert subscripts to indices?  Let me illustrate with a very\r\n% small example.\r\nmatrix = [ -1 1 0; 2 0 -2; 0 3 -3]\r\n[rows,cols] = find(matrix==0)\r\n%%\r\n% Now let's see what I get if I use the subscripts to address the selected\r\n% elements:\r\nmatrix(rows,cols)\r\n%%\r\n% I get the full matrix back, even though I selected only 3 elements.\r\n% This definitely surprised me when I first encountered this.  What's\r\n% happening?\r\n%%\r\n% MATLAB matches each row element with each column element.  \r\n% |matrix([1 2 3],2)| returns the elements from rows 1 through 3 in column\r\n% 1.\r\nmatrix(1:3,2)\r\n%%\r\n% To learn more about indexing in general, you might want to read\r\n% <https:\/\/blogs.mathworks.com\/loren\/?s=essence these posts> or search the\r\n% MATLAB documentation.\r\n%% Method #2 - Using Indices of Keepers\r\n% Here we used the single output form of |find| which returns indices\r\n% instead of subscripts.\r\nindA = find(A > (17^2)\/2);\r\nResult2 = zeros(size(A));\r\nResult2(indA) = A(indA);\r\nisequal(Result, Result2)\r\n%% Method #3 - Using Logical Keepers\r\n% We'll try keeping about half of the elements unchanged.  \r\nkeepA = (A > (17^2)\/2);\r\nResult3 = zeros(size(A));\r\nResult3(keepA) = A(keepA);\r\nisequal(Result, Result3)\r\n%% \r\n% |keepA| is a <https:\/\/www.mathworks.com\/help\/matlab\/ref\/logical.html |logical|> matrix\r\n% the same size as |A|.  I use logical indexing to populate |Result3| with\r\n% the chosen values from |A|.\r\n%% Method #4 - Subscripts for Elements to Set to Zero\r\n% If instead we have a list of candidates to set to 0, we have an easier time\r\n% since we don't need to start off with a matrix of |zeros|.  Instead we\r\n% start with a copy of |A|.  \r\nResult4 = A;\r\n[rnotA,cnotA] = find(A <= (17^2)\/2);\r\n%% \r\n% Convert indices to subscripts, as in method #1.\r\nindices = sub2ind(size(A),rnotA,cnotA);\r\n%%\r\n% Now zero out the selected matrix elements.\r\nResult4(indices) = 0;\r\nisequal(Result, Result4)\r\n%% Method #5 - Indices for Elements to Set to Zero\r\n% If we're instead given indices, we simply skip the step of converting\r\n% subscripts and follow similar logic to that in method #4.\r\nResult5 = A;\r\nindnotA = find(A <= (17^2)\/2);\r\nResult5(indnotA) = 0;\r\nisequal(Result, Result5)\r\n%% Method #6 - Using Logical Arrays to Specify Zero Elements\r\n% Finally, if we have a mask for the values to set to 0, we simply use it to\r\n% select and set elements.\r\nResult6 = A;\r\nkeepnotA = (A <= (17^2)\/2);\r\nResult6(keepnotA) = 0;\r\nisequal(Result, Result6)\r\n%% Which Method(s) Do You Prefer?\r\n% Which method or methods do you naturally find yourself using?  Do you\r\n% ever invert the logic of your algorithm to fit your way of thinking about\r\n% addressing the data (the ins or the outs)?  Please post your thoughts\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=138#respond here>.  I look forward\r\n% to seeing them.\r\n##### SOURCE END ##### 73889325f9414369b5488daea331b0f1\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Using MATLAB, there are several ways to identify elements from an array for which you wish to perform some action. Depending\r\n         on how you've chosen the elements, you may either... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2008\/05\/14\/acting-on-specific-elements\/\">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\/138"}],"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=138"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/138\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=138"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=138"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=138"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}