Message Boards Message Boards

0
|
5170 Views
|
1 Reply
|
1 Total Likes
View groups...
Share
Share this post:

Compute Nonzero components of a matrix in Mathematica

Posted 6 years ago

I'm trying to get rid of all of the nonzero terms in my matrix gamma. My current code works up until the last line of coding.

x = {r, \[Theta], \[Phi]} ;

R = {r Sin[\[Theta]] Cos[\[Phi]], r Sin[\[Theta]] Sin[\[Phi]],  r Cos[\[Theta]]};

e = Table[D[R, x[[i]]], {i, 1, 3}];

g = Simplify[Table[e[[i]].e[[j]], {i, 3}, {j, 3}]];

ginv = Inverse[g];

\[CapitalGamma] =  Table[Sum[  1/2 ginv[[i, l]] (D[g[[l, j]], x[[k]]] + D[g[[l, k]], x[[j]]] -  D[g[[j, k]], x[[l]]]), {l, 3}], {i, 3}, {j, 3}, {k, 3}];

Answer = If[\[CapitalGamma][[i, j, k]] =!= 0, Print[\[CapitalGamma][[i, j, k]]]] /. {i -> 1, j -> 1, k -> 1}
POSTED BY: Ray Hernandez
Posted 6 years ago

With your current code you'd need some looping mechanism to iterate the If statement over each possible value for i, j, and k.

If you just want to replace every non-zero element with 1, however, I would just do the following (using Replace, and targeting non-zero elements):

In[1]:= x = {r, t, phi};

In[2]:= R = {r Sin[t] Cos[phi], r Sin[t] Sin[phi], r Cos[t]};

In[3]:= e = Table[D[R, x[[i]]], {i, 1, 3}];

In[4]:= g = Simplify[Table[e[[i]].e[[j]], {i, 3}, {j, 3}]];

In[5]:= ginv = Inverse[g];

In[6]:= capitalGamma = 
  Table[Sum[
    1/2 ginv[[i, l]] (D[g[[l, j]], x[[k]]] + D[g[[l, k]], x[[j]]] - 
       D[g[[j, k]], x[[l]]]), {l, 3}], {i, 3}, {j, 3}, {k, 3}];

In[7]:= Replace[capitalGamma, (x_ /; x =!= 0 :> 1), {3}]

Out[7]= {{{0, 0, 0}, {0, 1, 0}, {0, 0, 1}}, {{0, 1, 0}, {1, 0, 0}, {0,
    0, 1}}, {{0, 0, 1}, {0, 0, 1}, {1, 1, 0}}}

No doubt other solutions exist, though.

POSTED BY: Kyle Martin
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract