Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since matrices are stored in mode of numeric, type of integer/double, and storage mode integer/double (assuming that matrix holds numerical values) you can use simple square bracket indexing to address specific values in them, e.g.</p> <pre><code># create dummy data &gt; m &lt;- matrix(rnorm(25), 5) &gt; mode(m) # check mode [1] "numeric" &gt; typeof(m) # check type [1] "double" &gt; storage.mode(m) [1] "double" </code></pre> <p>Now, in order to create diagonal matrix, you can use <code>lower.tri</code> and <code>upper.tri</code> functions, which return logical values for matrix elements beneath and above the main diagonal, respectively.</p> <p>You can use <code>lower.tri</code> and <code>upper.tri</code> functions to set off-diagonal elements to 0.</p> <pre><code>&gt; m[lower.tri(m)] &lt;- 0 &gt; m[upper.tri(m)] &lt;- 0 &gt; m [,1] [,2] [,3] [,4] [,5] [1,] 0.3356640 0.0000000 0.0000000 0.000000 0.0000000 [2,] 0.0000000 -0.2940369 0.0000000 0.000000 0.0000000 [3,] 0.0000000 0.0000000 -0.4490546 0.000000 0.0000000 [4,] 0.0000000 0.0000000 0.0000000 -1.093924 0.0000000 [5,] 0.0000000 0.0000000 0.0000000 0.000000 0.3199157 </code></pre> <p>You can, of course, set any constant to lower/upper diagonal elements, be it numerical, character, logical, NA, etc...</p> <p>Once you have set zeros as an off-diagonal elements, you can simply use square-bracket indexing. A little diversion: bare in mind that mathematically, vectors are special cases of matrices (and <em>vice versa</em>), but the same doesn't stand for <em>R</em>:</p> <pre><code>&gt; is.vector(m) [1] FALSE &gt; is.matrix(1:10) [1] FALSE </code></pre> <p>But, finally, you <strong>can</strong> do:</p> <pre><code>&gt; m[m == 0] &lt;- 1 </code></pre> <p>This will insert 1 in matrix wherever zeros occur. You can use <code>diag</code> function to access/change the diagonal elements, for example:</p> <pre><code>&gt; m[m == 1] &lt;- 0 &gt; diag(m) &lt;- rep(pi, 5) </code></pre> <p>will change your diagonal matrix to scalar one.</p> <p>After this boring post of mine, let us all hope that it helped someone, somehow...</p> <p>Cheers!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload