Changing iteration variable in Do loopChanging a Part of a variable within ParallelDoIterating FindRoot to solve a differential equationBeginners problem, Do Loop, Eigenfunction iterationExecute a notebook with a changing variablesuccessive iterationHow do I use the values generated in a for-loop in my first iteration to my next iteration?While loop with changing variable , NDSolve and an IntegralHow do I repeat the number of times a nested for loop does an iteration?Evaluating number of iteration with a certain map with WhileThe variable in the While loop does not change

Why force the nose of 737 Max down in the first place?

8086 stack segment and avoiding overflow in interrupts

GNU GPL V3 with no code change disclosure

Nuclear breeder/reactor plant controlled by two A.I. makes too much power

If the Moon were impacted by a suitably sized meteor, how long would it take to impact the Earth?

Desktop app status bar: Notification vs error message

Is there an antonym(a complementary antonym) for "spicy" or "hot" regarding food (I DO NOT mean "seasoned" but "hot")?

Wrapping IMemoryCache with SemaphoreSlim

Rampant sharing of authorship among colleagues in the name of "collaboration". Is not taking part in it a death knell for a future in academia?

Why is it "on the inside" and not "in the inside"?

How to season a character?

How can Paypal know my card is being used in another account?

Should I accept an invitation to give a talk from someone who might review my proposal?

What is a good example for artistic ND filter applications?

How well would the Moon protect the Earth from an Asteroid?

Why were contact sensors put on three of the Lunar Module's four legs? Did they ever bend and stick out sideways?

What would the United Kingdom's "optimal" Brexit deal look like?

Why was the LRV's speed gauge displaying metric units?

Is it okay for me to decline a project on ethical grounds?

2010 (?) science fiction TV show with new world

What do I lose by going Paladin 17 / Warlock 3, instead of taking 1 additional level or 1 fewer level in Warlock?

Is it safe if the neutral lead is exposed and disconnected?

Is there a word to describe someone who is, or the state of being, content with hanging around others without interacting with them?

Why does the Eurostar not show youth pricing?



Changing iteration variable in Do loop


Changing a Part of a variable within ParallelDoIterating FindRoot to solve a differential equationBeginners problem, Do Loop, Eigenfunction iterationExecute a notebook with a changing variablesuccessive iterationHow do I use the values generated in a for-loop in my first iteration to my next iteration?While loop with changing variable , NDSolve and an IntegralHow do I repeat the number of times a nested for loop does an iteration?Evaluating number of iteration with a certain map with WhileThe variable in the While loop does not change






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


I want to generate random positive hermitian matrices, I start with such a code



rho11R = Table[RandomReal[], i, 1, 4];
rho10R = Table[RandomComplex[], i, 1, 4];
Do[If[rho11R[[i]] - rho11R[[i]]^2 -
rho10R[[i]]*Conjugate[rho10R[[i]]] >= 0,
Nothing, rho10R[[i]] = RandomComplex[], --i], i, 1,
4];
rhoR = Table[rho11R[[i]], rho10R[[i]], Conjugate[rho10R[[i]]],
1 - rho11R[[i]], i, 1, 4]


This does not work, as the matrices I get are in general not positive.
The problem is my If function, which does not seem to change the iteration variable i to i-1, when the condition for positivity is not fulfilled (so that I can get new random variable for rho10R[[I]] and again check the condition for positivity). How can I reach this?










share|improve this question









$endgroup$









  • 1




    $begingroup$
    Have you tried a While[] loop instead?
    $endgroup$
    – Somos
    Jul 19 at 15:53










  • $begingroup$
    I assume that by positive you mean positive semi-definite, right?
    $endgroup$
    – Roman
    Jul 19 at 17:04

















2












$begingroup$


I want to generate random positive hermitian matrices, I start with such a code



rho11R = Table[RandomReal[], i, 1, 4];
rho10R = Table[RandomComplex[], i, 1, 4];
Do[If[rho11R[[i]] - rho11R[[i]]^2 -
rho10R[[i]]*Conjugate[rho10R[[i]]] >= 0,
Nothing, rho10R[[i]] = RandomComplex[], --i], i, 1,
4];
rhoR = Table[rho11R[[i]], rho10R[[i]], Conjugate[rho10R[[i]]],
1 - rho11R[[i]], i, 1, 4]


This does not work, as the matrices I get are in general not positive.
The problem is my If function, which does not seem to change the iteration variable i to i-1, when the condition for positivity is not fulfilled (so that I can get new random variable for rho10R[[I]] and again check the condition for positivity). How can I reach this?










share|improve this question









$endgroup$









  • 1




    $begingroup$
    Have you tried a While[] loop instead?
    $endgroup$
    – Somos
    Jul 19 at 15:53










  • $begingroup$
    I assume that by positive you mean positive semi-definite, right?
    $endgroup$
    – Roman
    Jul 19 at 17:04













2












2








2





$begingroup$


I want to generate random positive hermitian matrices, I start with such a code



rho11R = Table[RandomReal[], i, 1, 4];
rho10R = Table[RandomComplex[], i, 1, 4];
Do[If[rho11R[[i]] - rho11R[[i]]^2 -
rho10R[[i]]*Conjugate[rho10R[[i]]] >= 0,
Nothing, rho10R[[i]] = RandomComplex[], --i], i, 1,
4];
rhoR = Table[rho11R[[i]], rho10R[[i]], Conjugate[rho10R[[i]]],
1 - rho11R[[i]], i, 1, 4]


This does not work, as the matrices I get are in general not positive.
The problem is my If function, which does not seem to change the iteration variable i to i-1, when the condition for positivity is not fulfilled (so that I can get new random variable for rho10R[[I]] and again check the condition for positivity). How can I reach this?










share|improve this question









$endgroup$




I want to generate random positive hermitian matrices, I start with such a code



rho11R = Table[RandomReal[], i, 1, 4];
rho10R = Table[RandomComplex[], i, 1, 4];
Do[If[rho11R[[i]] - rho11R[[i]]^2 -
rho10R[[i]]*Conjugate[rho10R[[i]]] >= 0,
Nothing, rho10R[[i]] = RandomComplex[], --i], i, 1,
4];
rhoR = Table[rho11R[[i]], rho10R[[i]], Conjugate[rho10R[[i]]],
1 - rho11R[[i]], i, 1, 4]


This does not work, as the matrices I get are in general not positive.
The problem is my If function, which does not seem to change the iteration variable i to i-1, when the condition for positivity is not fulfilled (so that I can get new random variable for rho10R[[I]] and again check the condition for positivity). How can I reach this?







procedural-programming






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jul 19 at 15:25









AgnieszkaAgnieszka

10610 bronze badges




10610 bronze badges










  • 1




    $begingroup$
    Have you tried a While[] loop instead?
    $endgroup$
    – Somos
    Jul 19 at 15:53










  • $begingroup$
    I assume that by positive you mean positive semi-definite, right?
    $endgroup$
    – Roman
    Jul 19 at 17:04












  • 1




    $begingroup$
    Have you tried a While[] loop instead?
    $endgroup$
    – Somos
    Jul 19 at 15:53










  • $begingroup$
    I assume that by positive you mean positive semi-definite, right?
    $endgroup$
    – Roman
    Jul 19 at 17:04







1




1




$begingroup$
Have you tried a While[] loop instead?
$endgroup$
– Somos
Jul 19 at 15:53




$begingroup$
Have you tried a While[] loop instead?
$endgroup$
– Somos
Jul 19 at 15:53












$begingroup$
I assume that by positive you mean positive semi-definite, right?
$endgroup$
– Roman
Jul 19 at 17:04




$begingroup$
I assume that by positive you mean positive semi-definite, right?
$endgroup$
– Roman
Jul 19 at 17:04










3 Answers
3






active

oldest

votes


















4












$begingroup$

This is one the cases where For can be helpful (generally it's just more complicated.) With For, you can manipulate the iteration variable, which you cannot do with Do.



Example:



For[
i = 1,
i <= 4,
i++,
If[
i == 2,
Print[i++],
Print[i]
]
]


This prints 1, 2, 4.



Another option is to use While, as Somos wrote in a comment.






share|improve this answer









$endgroup$






















    4












    $begingroup$

    A much easier way to construct random positive semi-definite Hermitian matrices is to start with Gaussian random matrices and Hermitian-square them:



    randommatrix[n_Integer?Positive] := 
    RandomVariate[NormalDistribution[], n, n, 2].1, I

    randomHermitian[n_Integer?Positive] :=
    (# + ConjugateTranspose[#])/2 &[ConjugateTranspose[#].# &[randommatrix[n]]]


    In this way you don't need to reject anything.



    Test:



    randomHermitian[10] // Eigenvalues
    (* 71.4553, 53.6575, 46.3275, 31.8263, 21.4754,
    12.9687, 7.36107, 4.40568, 1.23665, 0.199904 *)


    There is of course the question of the measure (distribution) from which you pull the random matrices; you'd have to be more specific in your question to address this point.



    Thanks to @mikado for pointing out that Hermitian symmetrization is needed to avoid generating matrices that are almost-but-not-quite Hermitian because of numerical precision limits.






    share|improve this answer











    $endgroup$










    • 1




      $begingroup$
      While the matrices you generate are Hermitian by construction, they may not be exactly, because of rounding errors. It is good practice to force to Hermitian, by averaging with the conjugate transpose.
      $endgroup$
      – mikado
      Jul 19 at 22:14


















    0












    $begingroup$

    The following is a more "functional" way of doing acceptance/rejection



    mtx := RandomComplex[1+I, 2, 2]

    pmtx := Module[m = mtx, m1, m1 = Chop[m + ConjugateTranspose[m]];
    If[PositiveDefiniteMatrixQ[m1], m1, pmtx]]


    You can then generate a list of positive definite matrices of any length e.g.



    Table[pmtx, 20] 


    (Note: I'm not addressing the question of whether this gives an appropriate distribution of random matrices)






    share|improve this answer









    $endgroup$

















      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "387"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f202385%2fchanging-iteration-variable-in-do-loop%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4












      $begingroup$

      This is one the cases where For can be helpful (generally it's just more complicated.) With For, you can manipulate the iteration variable, which you cannot do with Do.



      Example:



      For[
      i = 1,
      i <= 4,
      i++,
      If[
      i == 2,
      Print[i++],
      Print[i]
      ]
      ]


      This prints 1, 2, 4.



      Another option is to use While, as Somos wrote in a comment.






      share|improve this answer









      $endgroup$



















        4












        $begingroup$

        This is one the cases where For can be helpful (generally it's just more complicated.) With For, you can manipulate the iteration variable, which you cannot do with Do.



        Example:



        For[
        i = 1,
        i <= 4,
        i++,
        If[
        i == 2,
        Print[i++],
        Print[i]
        ]
        ]


        This prints 1, 2, 4.



        Another option is to use While, as Somos wrote in a comment.






        share|improve this answer









        $endgroup$

















          4












          4








          4





          $begingroup$

          This is one the cases where For can be helpful (generally it's just more complicated.) With For, you can manipulate the iteration variable, which you cannot do with Do.



          Example:



          For[
          i = 1,
          i <= 4,
          i++,
          If[
          i == 2,
          Print[i++],
          Print[i]
          ]
          ]


          This prints 1, 2, 4.



          Another option is to use While, as Somos wrote in a comment.






          share|improve this answer









          $endgroup$



          This is one the cases where For can be helpful (generally it's just more complicated.) With For, you can manipulate the iteration variable, which you cannot do with Do.



          Example:



          For[
          i = 1,
          i <= 4,
          i++,
          If[
          i == 2,
          Print[i++],
          Print[i]
          ]
          ]


          This prints 1, 2, 4.



          Another option is to use While, as Somos wrote in a comment.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jul 19 at 16:17









          C. E.C. E.

          53.4k3 gold badges102 silver badges210 bronze badges




          53.4k3 gold badges102 silver badges210 bronze badges


























              4












              $begingroup$

              A much easier way to construct random positive semi-definite Hermitian matrices is to start with Gaussian random matrices and Hermitian-square them:



              randommatrix[n_Integer?Positive] := 
              RandomVariate[NormalDistribution[], n, n, 2].1, I

              randomHermitian[n_Integer?Positive] :=
              (# + ConjugateTranspose[#])/2 &[ConjugateTranspose[#].# &[randommatrix[n]]]


              In this way you don't need to reject anything.



              Test:



              randomHermitian[10] // Eigenvalues
              (* 71.4553, 53.6575, 46.3275, 31.8263, 21.4754,
              12.9687, 7.36107, 4.40568, 1.23665, 0.199904 *)


              There is of course the question of the measure (distribution) from which you pull the random matrices; you'd have to be more specific in your question to address this point.



              Thanks to @mikado for pointing out that Hermitian symmetrization is needed to avoid generating matrices that are almost-but-not-quite Hermitian because of numerical precision limits.






              share|improve this answer











              $endgroup$










              • 1




                $begingroup$
                While the matrices you generate are Hermitian by construction, they may not be exactly, because of rounding errors. It is good practice to force to Hermitian, by averaging with the conjugate transpose.
                $endgroup$
                – mikado
                Jul 19 at 22:14















              4












              $begingroup$

              A much easier way to construct random positive semi-definite Hermitian matrices is to start with Gaussian random matrices and Hermitian-square them:



              randommatrix[n_Integer?Positive] := 
              RandomVariate[NormalDistribution[], n, n, 2].1, I

              randomHermitian[n_Integer?Positive] :=
              (# + ConjugateTranspose[#])/2 &[ConjugateTranspose[#].# &[randommatrix[n]]]


              In this way you don't need to reject anything.



              Test:



              randomHermitian[10] // Eigenvalues
              (* 71.4553, 53.6575, 46.3275, 31.8263, 21.4754,
              12.9687, 7.36107, 4.40568, 1.23665, 0.199904 *)


              There is of course the question of the measure (distribution) from which you pull the random matrices; you'd have to be more specific in your question to address this point.



              Thanks to @mikado for pointing out that Hermitian symmetrization is needed to avoid generating matrices that are almost-but-not-quite Hermitian because of numerical precision limits.






              share|improve this answer











              $endgroup$










              • 1




                $begingroup$
                While the matrices you generate are Hermitian by construction, they may not be exactly, because of rounding errors. It is good practice to force to Hermitian, by averaging with the conjugate transpose.
                $endgroup$
                – mikado
                Jul 19 at 22:14













              4












              4








              4





              $begingroup$

              A much easier way to construct random positive semi-definite Hermitian matrices is to start with Gaussian random matrices and Hermitian-square them:



              randommatrix[n_Integer?Positive] := 
              RandomVariate[NormalDistribution[], n, n, 2].1, I

              randomHermitian[n_Integer?Positive] :=
              (# + ConjugateTranspose[#])/2 &[ConjugateTranspose[#].# &[randommatrix[n]]]


              In this way you don't need to reject anything.



              Test:



              randomHermitian[10] // Eigenvalues
              (* 71.4553, 53.6575, 46.3275, 31.8263, 21.4754,
              12.9687, 7.36107, 4.40568, 1.23665, 0.199904 *)


              There is of course the question of the measure (distribution) from which you pull the random matrices; you'd have to be more specific in your question to address this point.



              Thanks to @mikado for pointing out that Hermitian symmetrization is needed to avoid generating matrices that are almost-but-not-quite Hermitian because of numerical precision limits.






              share|improve this answer











              $endgroup$



              A much easier way to construct random positive semi-definite Hermitian matrices is to start with Gaussian random matrices and Hermitian-square them:



              randommatrix[n_Integer?Positive] := 
              RandomVariate[NormalDistribution[], n, n, 2].1, I

              randomHermitian[n_Integer?Positive] :=
              (# + ConjugateTranspose[#])/2 &[ConjugateTranspose[#].# &[randommatrix[n]]]


              In this way you don't need to reject anything.



              Test:



              randomHermitian[10] // Eigenvalues
              (* 71.4553, 53.6575, 46.3275, 31.8263, 21.4754,
              12.9687, 7.36107, 4.40568, 1.23665, 0.199904 *)


              There is of course the question of the measure (distribution) from which you pull the random matrices; you'd have to be more specific in your question to address this point.



              Thanks to @mikado for pointing out that Hermitian symmetrization is needed to avoid generating matrices that are almost-but-not-quite Hermitian because of numerical precision limits.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jul 20 at 18:18

























              answered Jul 19 at 17:02









              RomanRoman

              14.9k1 gold badge20 silver badges51 bronze badges




              14.9k1 gold badge20 silver badges51 bronze badges










              • 1




                $begingroup$
                While the matrices you generate are Hermitian by construction, they may not be exactly, because of rounding errors. It is good practice to force to Hermitian, by averaging with the conjugate transpose.
                $endgroup$
                – mikado
                Jul 19 at 22:14












              • 1




                $begingroup$
                While the matrices you generate are Hermitian by construction, they may not be exactly, because of rounding errors. It is good practice to force to Hermitian, by averaging with the conjugate transpose.
                $endgroup$
                – mikado
                Jul 19 at 22:14







              1




              1




              $begingroup$
              While the matrices you generate are Hermitian by construction, they may not be exactly, because of rounding errors. It is good practice to force to Hermitian, by averaging with the conjugate transpose.
              $endgroup$
              – mikado
              Jul 19 at 22:14




              $begingroup$
              While the matrices you generate are Hermitian by construction, they may not be exactly, because of rounding errors. It is good practice to force to Hermitian, by averaging with the conjugate transpose.
              $endgroup$
              – mikado
              Jul 19 at 22:14











              0












              $begingroup$

              The following is a more "functional" way of doing acceptance/rejection



              mtx := RandomComplex[1+I, 2, 2]

              pmtx := Module[m = mtx, m1, m1 = Chop[m + ConjugateTranspose[m]];
              If[PositiveDefiniteMatrixQ[m1], m1, pmtx]]


              You can then generate a list of positive definite matrices of any length e.g.



              Table[pmtx, 20] 


              (Note: I'm not addressing the question of whether this gives an appropriate distribution of random matrices)






              share|improve this answer









              $endgroup$



















                0












                $begingroup$

                The following is a more "functional" way of doing acceptance/rejection



                mtx := RandomComplex[1+I, 2, 2]

                pmtx := Module[m = mtx, m1, m1 = Chop[m + ConjugateTranspose[m]];
                If[PositiveDefiniteMatrixQ[m1], m1, pmtx]]


                You can then generate a list of positive definite matrices of any length e.g.



                Table[pmtx, 20] 


                (Note: I'm not addressing the question of whether this gives an appropriate distribution of random matrices)






                share|improve this answer









                $endgroup$

















                  0












                  0








                  0





                  $begingroup$

                  The following is a more "functional" way of doing acceptance/rejection



                  mtx := RandomComplex[1+I, 2, 2]

                  pmtx := Module[m = mtx, m1, m1 = Chop[m + ConjugateTranspose[m]];
                  If[PositiveDefiniteMatrixQ[m1], m1, pmtx]]


                  You can then generate a list of positive definite matrices of any length e.g.



                  Table[pmtx, 20] 


                  (Note: I'm not addressing the question of whether this gives an appropriate distribution of random matrices)






                  share|improve this answer









                  $endgroup$



                  The following is a more "functional" way of doing acceptance/rejection



                  mtx := RandomComplex[1+I, 2, 2]

                  pmtx := Module[m = mtx, m1, m1 = Chop[m + ConjugateTranspose[m]];
                  If[PositiveDefiniteMatrixQ[m1], m1, pmtx]]


                  You can then generate a list of positive definite matrices of any length e.g.



                  Table[pmtx, 20] 


                  (Note: I'm not addressing the question of whether this gives an appropriate distribution of random matrices)







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jul 19 at 22:03









                  mikadomikado

                  7,3301 gold badge9 silver badges29 bronze badges




                  7,3301 gold badge9 silver badges29 bronze badges






























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Mathematica Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      Use MathJax to format equations. MathJax reference.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f202385%2fchanging-iteration-variable-in-do-loop%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

                      Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                      Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form