1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: MATLAB programming assignment (for loop)

  1. Mar 29, 2012 #1
    1. The problem statement, all variables and given/known data
    (see attached file)

    2. Relevant equations
    (see attached file)

    3. The attempt at a solution
    isbn=input('Enter 9 Letter ISBN number: ','s');
    for i=1:1:length(isbn)


    %somewhere in here I need code to add all the checks found in the loop

    checksum=mod(check%not correct,11)

    So I have gotten the loop to visit all the digits separately and multiply it by the loop variable. Now all I need is some way to add all of those values into one. From there I use the modulus function and that's basically it. My prof gave a few hints. She said an if statement would be used, but that's probably for when the mod of the value will equal 10 and I need to display an X.

    Also, I'm assuming I need to use a string concatenation at some point since it reminds me about it. Will that be used to put together the output at the end?

    I realize this is probably a very simple exercise but this is my first effort using loops so I'm still trying to get a grasp on it

    Attached Files:

    Last edited: Mar 29, 2012
  2. jcsd
  3. Mar 29, 2012 #2
    You need a running total for the checksum. In your current for loop, each increment of your loop variable, you erase what was originally in check and replace it with num*i. Also, cat seems undefined. Take a look at this piece of code that correctly gives the checksum:

    Code (Text):

    isbn=input('Enter 9 Digit ISBN number: ','s');
    check = 0;
    for k = 1:length(isbn)
        check = check + str2double(isbn(k))*k;

    checksum = mod(check,11) %correct now
    The difference is I say check = check + number. So I say the new check is equal to whatever was in there before plus this additional number. It is important to realize that check = check + number isn't the same kind of equal sign as in algebra. Also, I define check = 0 before entering the loop. Otherwise, I will get an error, because the code will say new check = old check + number. But old check doesn't exist!

    On a side note, the default increment is 1, so you don't need to put it in your for loop if you want to leave it out.

    I imagine her idea behind mentioning string concatenation was to provide a tool for you to create the output. I notice in the screenshot there are dashes, numbers, and potentially an X. So you can create this output string with a few concatenations.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook