0
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ Have you seen this? $\endgroup$ – J. M. will be back soon Jan 6 at 13:04
  • $\begingroup$ @J.M.iscomputer-less i will try to avoid For loop.But for the seek of answer can you help me to solve it?!! Thanks for your link $\endgroup$ – raihan hossain Jan 7 at 14:46
2
$\begingroup$

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}
$\endgroup$
  • $\begingroup$ only tangentially: in general, LinearSolve[A, B] is better to do than Inverse[A].B. $\endgroup$ – J. M. will be back soon Jan 5 at 4:54
  • $\begingroup$ @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 $\endgroup$ – raihan hossain Jan 5 at 6:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.