0

Consider the linear system AX=B,where A={{3, 0, 2}, {-3, 2, 2}, {2, -3, 3}},B={{3}, {-1}, {4}} and x={{x},{y},{z}}.So i tried like this:

A1 = {{, ,}, {, ,}, {, ,}}; A3 = {{, ,}, {, ,}, {, ,}}; A2 = {{, ,}, \
{, ,}, {, ,}}; For[i = 1, i <= 3, i++,
 For[j = 1, j <= 3, j++, 
  If[j == 1, A1[[i, j]] = B[[i, 1]], A1[[i, j]] = A[[i, j]]]]]; For[
 i = 1, i <= 3, i++,
 For[j = 1, j <= 3, j++, 
  If[j == 2, A2[[i, j]] = B[[i, 1]], A2[[i, j]] = A[[i, j]]]]]; For[
 i = 1, i <= 3, i++,
 For[j = 1, j <= 3, j++, 
  If[j == 3, A3[[i, j]] = B[[i, 1]], 
   A3[[i, j]] = A[[i, j]]]]]; x = (Det[A1]/Det[A]); y = (Det[A2]/
   Det[A]); z = (Det[A3]/Det[A]); Print["x=", x, " y=", y, " z=", z]

But i want to do this using only one loop.i am new user of mathematica.So can Anyone help me to figure out this. Any hints or solution will be appreciated.
Thanks in Advanced.

1 Answers1

2

If you just want the solution, you may use Inverse[A].B. If you want to illustrate Cramer's rule, the A1, A2, A3 matrices do not need to be constructed via any loop (using lower case letter below):

a1 = Join[B, A[[;; , 2 ;; 3]], 2];
a2 = Join[A[[;; , 1 ;; 1]], B, A[[;; , 3 ;; 3]], 2];
a3 = Join[A[[;; , 1 ;; 2]], B, 2];

then

x = Det[a1]/Det[A]
y = Det[a2]/Det[A]
z = Det[a3]/Det[A]

gives 13/23, -7/23, 15/23. You can verify that the a1 through a3 matrices are identical to your A1 ... A3.

For more on the use of Join, refer to the documentation or here. Also, to initialize a matrix for later use you may try something like Table[Null, 3, 3] instead of typing out {{, ,}, {, ,}, {, ,}}

Alternatively, you may just use:

a1 = a2 = a3 = A;
a1[[;; , 1]] = a2[[;; , 2]] = a3[[;; , 3]] = Flatten[B];
{x, y, z} = Det[#]/Det[A] & /@ {a1, a2, a3}
egwene sedai
  • 2,355
  • 16
  • 24
  • only tangentially: in general, LinearSolve[A, B] is better to do than Inverse[A].B. – J. M.'s missing motivation Jan 05 '19 at 04:54
  • @egwene sedai thanks for your answer but i really want to do it by loop.Yes i understood using 'LinearSolve[A,B]' maybe less working.but i want to learn it by loop method.could you update your answer? Thanks again – raihan hossain Jan 05 '19 at 06:31