Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Another Noob MATLAB Question - For loop

  1. Jul 5, 2011 #1
    1. The problem statement, all variables and given/known data

    Use the primes function to create a list of all the primes below 100. Now use a for loop to multiply adjacent values together. For example the first 4 primes numbers are

    2 3 5 7

    your calculation would be

    2*3 3*5 5*7

    which gives

    6 15 35

    2. Relevant equations

    3. The attempt at a solution
    Ok I spent a very long time trying to solve this problem. I eventually solved it with the following program.

    i uploaded a easier version to read, i myself couldn't stand even looking at my program below so i took a snip of it in a easier to read form

    for b=primes(100);
    if z>1;

    which produces the following results, just the way I wanted them to

    ans =

    Columns 1 through 9

    6 15 35 77 143 221 323 437 667

    Columns 10 through 18

    899 1147 1517 1763 2021 2491 3127 3599 4087

    Columns 19 through 24

    4757 5183 5767 6557 7387 8633

    my only question and concern is why in my program must I include b=primes(100); after the end statement? I thought it was enough for me to just define it once and only once after the for command? I however noticed when I did so that b would get defined as 2 for some strange reason and that's it not what primes(100) is suppose to produce.

    I was hoping someone could explain this to me. Thanks in advance!
    Last edited: Jul 6, 2011
  2. jcsd
  3. Jul 6, 2011 #2
    Check attachments

    Attached Files:

  4. Jul 6, 2011 #3

    You don't define b as a vector before the loop, you just run through it in the for loop, so b in the loop takes on a integer value, and not a vector.

    Generally: don't use b as running variable in loop, while re-assigning it a value IN the loop. Bound for troubles.

    Define b before the for loop, and use a running variable i=1:1:a in the for loop.

  5. Jul 6, 2011 #4


    User Avatar
    Science Advisor

    Hi Greenprint, use "code" tags to preserve formatting in posts.

    That's really bad use of a for loop as outlined by Laiva above. Set up your for loop limits before the loop, something like the following.

    Code (Text):

    for k=1:sp
    Last edited: Jul 6, 2011
  6. Jul 7, 2011 #5
    thanks I think I better understand the loop commands now =)
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook