The function rgb2gray
eliminates hue and saturation and retains the information about luminance(brightness).
So, you can convert a pixel located at i and j into grayscale by using following formula.
Formula
grayScaleImage(i,j) = 0.298*img(i,j,1)+0.587*img(i,j,2)+0.114*img(i,j,3)
img(i,j,1) is value of RED pixel.
img(i,j,2) is value of GREEN pixel.
img(i,j,3) is value of BLUE pixel.
grayScaleImage(i,j) is value of the pixel in grayscale in range[0..255]
Psuedo Code
img = imread('example.jpg');
[r c colormap] = size(img);
for i=1:r
for j=1:c
grayScaleImg(i,j) = 0.298*img(i,j,1)+0.587*img(i,j,2)+0.114*img(i,j,3);
end
end
imshow(grayScaleImg);