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!

Can someone help me with this matlab code

  1. May 20, 2009 #1
    i need to build a code which asks the user for the size of the desired diamond and then draws it, i can get this to workl perfectly by using the fprintf command and building the diamond out of 4 parts,: see code-

    Code (Text):
    clc
    clear
    h=input('enter height of diamond :');
    y=1;
    while y<=h/2
        for x=1:h-1
            if x<=((h)/2-(y-1))
                fprintf(1,'*\t');
            end
            if x>(h)/2-(y-1) & x<(h)/2+(y-1)
                fprintf(1,'\t');
            end
            if x>=((h)/2+(y-1)) &x<=h-1
                fprintf(1,'*\t');
            end
        end
        y=y+1;
        fprintf(1,'\n')
    end

    while y>h/2 &y<=h
        for x=1:h-1
            if x<=((h)/2-(h-y))
                fprintf(1,'*\t');
            end
            if x>(h)/2-(h-y) & x<(h)/2+(h-y)
                fprintf(1,'\t');
            end
            if x>=((h)/2+(h-y)) &x<=h-1
                fprintf(1,'*\t');
            end
        end
        y=y+1;
        fprintf(1,'\n')
    end
    but for any even numbers i put in as my size, i get 2 extra asterixs on the corners, can anyone see how i chan get rid of them?
     
  2. jcsd
  3. May 21, 2009 #2

    MATLABdude

    User Avatar
    Science Advisor

    Look inside the loops that create the horizontal rows of asterisks. You actually have a degenerate case where two of the if statements get executed! (At the very top and very bottom rows)
     
  4. May 21, 2009 #3
    thats what i thought must be happening, but i cannot find where, could you show me
     
  5. May 21, 2009 #4

    MATLABdude

    User Avatar
    Science Advisor

  6. May 21, 2009 #5
    i think that the problem comes fro the 1st line, where (y-1)=0 therefore, (h)/2-(y-1) is equal to x>(h)/2+(y-1) and so both the 1st and 3rd if commands are executed,
    so i tried making one <= and one > but that messed up my whole diamond
     
  7. May 21, 2009 #6

    MATLABdude

    User Avatar
    Science Advisor

    Use some elseif statements to prevent the execution of more than one of the if statements:
    http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/brqy1c1-1.html#brqy1c1-3 [Broken]

    You could use a break statement, but this is considered very poor programming form.
     
    Last edited by a moderator: May 4, 2017
  8. May 21, 2009 #7
    thanks, works pefrectly
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook