Friday, April 13, 2012

Displaying a Pyramid on MATLAB

This script of codes demonstrates the usage of the fprintf function to properly insert spacings within MATLAB. It also demonstrates the use of nested for loops to make a two-dimensional representation. Given a positive odd integer n as the input, this code displays a pyramid of base length n and height of n/2.
%The input integer 'n' denotes the width of the base of the pyramid
%If 'n' is even, it'll be the same as making a (n-1) sized pyramid
function pyramid = input(n)
%The height of the pyramid will be (n+1)/2
for i=1:2:n
    %Spacings on the left: 'c' is used for a character here, in this case the empty space ' '
    for j=1:(n-i)/2
        fprintf('%c',' ')
    end
   
    %Actual pyramid marks
    for k=1:i
        fprintf('%c','*')
    end
   
    %Spacings on the right: same chunk of code as the code for the left spacings
    for j=1:(n-i)/2
        fprintf('%c',' ')
    end
   
    %Carriage return after each line
    fprintf('\n')
end
If n = 5, for example, the output will be like this:
    * 
  ***
*****
While using the fprintf function, care needs to be taken to ensure the use of the correct conversion letter. Refer to the link below for further references.

Source: