Monday, August 24, 2015

Inverse / Division of Matrix using Adjoint Method

Inverse.m

clc;
clear all;
close all;

disp('Inverse of a matrix using Adjoint Method')
        disp('------------------------------------------------')
        prompt = 'Enter the order of the matrix ';
        m = input(prompt);
        % initializes the variable M
        M=zeros(m,m);
N=zeros(m,m);
        % Entering random values in matrices
        for i=1:m
            for j=1:m
                M(i,j)=random('unid',10);
            end
        end
d = detrminant(M,m);
        disp('The determinant is ');
disp(num2str(d,2));
if d==0
disp('Matrix is not inversible');
else
cofactors(d,M,m,N,2,m); % N,2,m for separating division operation from inverse operation
end


detrminant.m

function d=detrminant(M,m)

det=0;
s=1;
N=zeros(m,m);
if (m==1)
d=M(1,1); return
else
det = 0;
for c=1:m
p = 1;
q = 1;
for i=1:m
for j=1:m
if (i~=1 && j~=c)
N(p,q)=M(i,j);
if (q<(m-1))
q=q+1;
else
q=1;
p=p+1;
end
end
end
end
det=det+s*(M(1,c)*detrminant(N,m-1));
s=-1*s;
end
end
d=det; return

cofactors.m

function cofactors(det,M,m,Q,u,f)

N=zeros(m,m);
fac=zeros(m,m);
for q=1:m
for p=1:m
m1 = 1;
n1 = 1;
for i=1:m
for j=1:m
if (i~=q && j~=p)
N(m1,n1) = M(i,j);
if (n1 < (m - 1))
n1=n1+1;
else
n1 = 1;
m1=m1+1;
end
end
end
end
fac(q,p)=power(-1,q+p)*detrminant(N,m-1);
end
end

trans(det,M,fac,m,Q,u,f); % transpose of cofactor matrix i.e. adjoint matrix

trans.m

function trans(det,mat,fac,r,Q,u,f)

N=zeros(r,r);
inv=zeros(r,r);

for i=1:r
for j=1:r
N(i,j)=fac(j,i);
end
end
for i=1:r
for j=1:r
inv(i,j)=N(i,j) / det;
end
end
disp('=============================================');
disp('     THE INVERSE OF THE MATRIX');
disp('=============================================');
disp(inv);
nonsingular(mat,inv,r,Q,u,f);

nonsingular.m

function nonsingular(mat,inv,r,Q,u,f)

if (u==2)
count=0;
I=zeros(r,r);
for i=1:r
for j=1:r
sum=0;
for k=1:r
sum=sum+mat(i,k)*inv(k,j);
end
I(i,j)=sum;
end
end    
disp('=============================================');
disp('     CHECK FOR SINGULAR OR NON-SINGULARITY');
disp('=============================================');
disp(I);
for i=1:r
for j=1:r
if(i==j && int8(I(i,j))==1)
count=count+1;
end
end
end
if(count==r)
disp('Non-Singular/Invertible Inverse Matrix');
else
disp('Singular/Non-Invertible Inverse Matrix');
end
elseif (u==1)
DIV=zeros(f,r);
for i=1:f
for j=1:r
sum=0;
for k=1:r
sum=sum+Q(i,k)*inv(k,j);
end
DIV(i,j)=sum;
end
end    
disp('=============================================');
disp('     DIVISION OF TWO MATRICES');
disp('=============================================');
disp(DIV);
end


Wednesday, September 17, 2014

Trapezoidal Method of numerical integration in C

#include<stdio.h>
#include<conio.h>

float f(float x){
float r;
r=2*x+1;
return r;
}

void main(){

float output;
float a,b;
float h,s;
int i,j;
int n;
clrscr();
printf("===========================================\n");
printf("           TRAPEZOIDAL RULE\n");
printf("===========================================\n");
printf("Enter the integral limit:-\n");
printf("-------------------------------------------\n");
printf("Lower limit value a: \n");
scanf("%f",&a);
printf("Upper limit value b: \n");
scanf("%f",&b);
printf("-------------------------------------------\n");
printf("Enter number of total intervals: \n");
scanf("%d",&n);
h=0.0;
h=(b-a)/n;
printf("____________________________________________\n");
printf("Resultant value of h is %.2f \n",h);
s=0.0;
s=f(a)+f(b);
printf("Resultant value of f(a) + f(b) is %.2f \n",s);
for (i=1;i<=n-1;i++)
{
s=s+2*f(a+i*h);
}
printf("Resultant value of whole summation of f(-) is %.2f\n",s);
output=1;
output=(h/2)*s;
printf("Output value of the integral is %.2f \n",output);
printf("____________________________________________\n");
printf("             GOOD LUCK\n");
getch();
}

Simpson's One-Third Rule of numerical integration in C

#include<stdio.h>
#include<conio.h>

float f(float x){
float r;
r=2*x+1;
return r;
}

void main(){

float output;
float a,b;
float h,s;
int i,j;
int n;
clrscr();
printf("===========================================\n");
printf("           SIMPSON'S ONE-THIRD RULE\n");
printf("===========================================\n");
printf("Enter the integral limit:-\n");
printf("-------------------------------------------\n");
printf("Lower limit value a: \n");
scanf("%f",&a);
printf("Upper limit value b: \n");
scanf("%f",&b);
printf("-------------------------------------------\n");
printf("Enter number of total intervals: \n");
scanf("%d",&n);
h=0.0;
h=(b-a)/(2*n);
printf("____________________________________________\n");
printf("Resultant value of h is %.2f \n",h);
s=0.0;
s=f(a)+f(b)+4*f(a+h);
printf("Resultant value of f(a) + f(b) is %.2f \n",s);
for (i=3;i<2*n;i+=2)
{
s+=2*f(a+(i-1)*h)+4*f(a+i*h);
}
printf("Resultant value of whole summation of f(-) is %.2f\n",s);
output=1;
output=(h/3)*s;
printf("Output value of the integral is %.2f \n",output);
printf("____________________________________________\n");
printf("             GOOD LUCK\n");
getch();
}

Tuesday, December 3, 2013

Write a program in MatLab to extract a part of image using without a function .


clc;
clear all;
close all;

A=imread('contrast (3).tif');
r=size(A,1)-1;
i=int32(rand(1,1)*r)+1; % +1 for random value always from 0
j=i+500;
if(j>size(A,1))
    d=j-size(A,1);
    j=j-d;
end
c=size(A,2)-1;
k=int32(rand(1,1)*c)+1; % +1 for random value always from 0
l=k+500;
if(l>size(A,2))
    d1=l-size(A,2);
    l=l-d1;
end
B=zeros(size(A,1),size(A,2));
x=i;
for p=i:j-1
    y=k;
    for q=k:l-1
        B(x,y)=A(p,q);
        y=y+1;
    end
    x=x+1;
end
B1 = mat2gray(B);
figure('Position',[10  50 1400 630]);
subplot(1,2,1),imshow(A),
ylabel('Original Image','Color','r','FontSize', 10,'FontAngle', 'italic');
subplot(1,2,2),imshow(B1),
ylabel('Sub Image','Color','r','FontSize', 10,'FontAngle', 'italic');

Write a program in MatLab to enhance brightness and contrast of RGB and Gray images.

clc;
clear all;
close all;

im=imread('contrast (3).tif');
d=ndims(im);
if(d==2)
%----------------------------------------------------------
%                       Gray Image
%----------------------------------------------------------
    im=double(im);
    [M N]=size(im);
    MN=M*N;
    sum=0;
    for i=1:M
        for j=1:N
            sum = sum + im(i,j);
        end
    end
    B=sum/MN;
    disp(['Brightness of an Gray Image is ',num2str(B)]);
    sum=0;
    for i=1:M
        for j=1:N
            S=im(i,j)-B;
            S=S^2;
            sum = sum + S;
        end
    end
    C=sum/MN;
    con=double(C)^0.5;
    disp(['Contrast of an Gray Image is ',num2str(con)]);
else
%----------------------------------------------------------
%                       RGB
%----------------------------------------------------------
    B_sum=0;
    C_sum=0;
    for k=1:3
        I=im(:,:,k);
        I=double(I);
        [M N]=size(I);
        MN=M*N;
        sum=0;
        for i=1:M
            for j=1:N
                sum = sum + I(i,j);
            end
        end
        B=sum/MN;
        B_sum=B_sum+B;
        sum=0;
        for i=1:M
            for j=1:N
                S=I(i,j)-B;
                S=S^2;
                sum = sum + S;
            end
        end
        C=sum/MN;
        con=double(C)^0.5;
        C_sum=C_sum+con;
    end
    disp(['Brightness of an RGB image is ',num2str(B_sum)]);
    disp(['Contrast of an RGB image is ',num2str(C_sum)]);
end

Write a program in MatLab to remove background of an image.


clc;
clear all;
close all;

f=imread('n.jpg');
f=rgb2gray(f);
sub=zeros(size(f));
[ROW COLUMN]=size(sub);
f=im2double(f);

% Global Thresholding
T=0.5*(min(f(:))+max(f(:)));
done=false;
while ~done
    g=f>=T;
    Tn=0.5*(mean(f(g))+mean(f(~g)));
    done=abs(T-Tn)<0.1;
    T=Tn;
end
r=im2bw(f,T);
R=double(r);
%Image Subtraction
for i=1:ROW
        for j=1:COLUMN
            sub(i,j)=R(i,j)-f(i,j);
        end
end
% Sliding Neighborhood Normalization
fun = @(x) mode(x(:));
B = nlfilter(sub,[3 3],fun);

figure;
subplot(2,2,1),imshow(f),title('Original Image');
subplot(2,2,2),imshow(r),title('Global Thresholding - Iterative Method');
subplot(2,2,3),imshow(sub),title('Subtracted Image');
subplot(2,2,4),imshow(B),title('Final Result');

Monday, December 2, 2013

Write a program to implement Histogram equilization using MatLab.


clc;
clear all;
close all;

A1=imread('E:\M.Tech\1st Semester\Image Processing\Lab\histogram.tif');
B1=A1;
[row column]=size(B1);
L=256;
MN=row*column;
nk=zeros(1,L); %nk is the number of pixels that have intensity rk.
for i=1:row
    for j=1:column
        nk(B1(i,j)+1)=nk(B1(i,j)+1)+1;
    end
end
% The probability of occurence of intensity level rk in a image pr(rk).
nk=nk/MN;
% Transformation T(rk):a output image is obtained by transforming each
% pixel in the input image with intensity rk into a corresponding pixel
% with level sk in the output image.
s=zeros(1,L);
sum=0;
for k=1:L
    sum=sum+nk(k);
    s(k)=round((L-1)*sum);
end
% Equalization
equalized=zeros(1,L);
for i=1:L
    equalized(s(i)+1)=equalized(s(i)+1)+nk(i);
end
% Convert the image using transformation s(k)
for i=1:row
    for j=1:column
        B1(i,j)=s(B1(i,j)+1);
    end
end

figure;
subplot(2,2,1),imshow(A1),title('Original image');
subplot(2,2,2),imshow(B1),title('Equalized image');
subplot(2,2,3),bar(nk,'g'),title('Histogram of Original');
subplot(2,2,4),bar(equalized,'g'),title('Equalized Histogram');

Monday, November 18, 2013

Write a program in MATLAB to generate a median of an image.

clc;
clear all;
close all;

A=imread('median.tif');
% Pad the matrix with zeros on all sides
modifyA=zeros(size(A)+2);
B=zeros(size(A));
% copy the original image matrix to the padded matrix
for x=1:size(A,1)
    for y=1:size(A,2)
        modifyA(x+1,y+1)=A(x,y);
    end
end
 
h = waitbar(0,'Calculating Median Operation please wait......');

% Let the window be an array store the 3-by-3 neighbour
% values in the array sort and find the middle element
     
for i= 1:size(modifyA,1)-2
    for j=1:size(modifyA,2)-2
        window=zeros(9,1);
        inc=1;
        for x=1:3
            for y=1:3
                window(inc,1)=modifyA(i+x-1,j+y-1);
                inc=inc+1;
            end
        end
        med=sort(window);
        % Place the median element in the output matrix
        B(i,j)=med(5);
    end
    waitbar(i/size(modifyA,1));
end
% Convert the output matrix to 0-255 range image type
B=uint8(B);
figure('Position',[100  100 1200 550]);
subplot(1,2,1),imshow(A),
ylabel('Image with salt-papper noise','Color','r','FontSize', 20,'FontAngle', 'italic');
subplot(1,2,2),imshow(B),
ylabel('Image after median filtering','Color','r','FontSize', 20,'FontAngle', 'italic');
close(h);

Write a program in MATLAB to design a Mask to generate a mean image considering 8 neighborhood.

clc;
clear all;
close all;

A=imread('median.tif');
A = im2double(A);
G=A;
% Pad the matrix with zeros on all sides
modifyA=zeros(size(A)+2);
% copy the original image matrix to the padded matrix
for x=1:size(A,1)
    for y=1:size(A,2)
        modifyA(x+1,y+1)=A(x,y);
    end
end

h = waitbar(0,'Calculating Arithmetic Mean Operation please wait......');
m=3;n=3;
       
for i= 1:size(modifyA,1)-2
    for j=1:size(modifyA,2)-2
        s=0;
        kernel = ones(m, n) / 9; % mxn(8-neighbor) mean kernel
        for x = 1:m
            for y = 1:n
                s=s+modifyA(i+x-1,j+y-1)*kernel(x,y);
            end
        end
        G(i,j)=s;
    end
    waitbar(i/size(modifyA,1));
end
figure('Position',[100  100 1200 550]);
subplot(1,2,1),imshow(A);
ylabel('salt-papper noise Image','Color','r','FontSize', 20,'FontAngle', 'italic');
subplot(1,2,2),imshow(G);
ylabel('Arithmetic mean filter','Color','r','FontSize', 20,'FontAngle', 'italic');
close(h);

Tuesday, November 5, 2013

Implementation of Frequency Reuse Factor in Mobile Computing using C

#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<math.h>

#define SIDE 30
#define PI 3.14159
#define X 300
#define Y 220

void draw_hexagon(int,int);
void recur_draw(int,int,int);
void frequency(int,int);

char *name[]={"Blue","Green","Cyan","Red","Magenta","Brown","Lightgray"};
int count=1;

void main(){
int gd=DETECT,gm;
int k=0,f=0;
initgraph(&gd,&gm,"C:\\TC\\BGI");
printf("Enter the value of Reuse Factor (k) ");
scanf("%d",&k);
printf("Enter the frequency range: ");
scanf("%d",&f);
draw_hexagon(X,Y);
recur_draw(X,Y,k);
frequency(f,k);
getch();
closegraph();
}
void draw_hexagon(int x,int y){
int x1,y1,x2,y2,i;
int degree=0;
x1=x+SIDE*cos((degree*PI)/180);
y1=y+SIDE*sin((degree*PI)/180);
setcolor(WHITE);
setlinestyle(0,0,3);
for(i=1;i<=6;i++){
degree=degree+60;
x2=x+SIDE*cos((degree*PI)/180);
y2=y+SIDE*sin((degree*PI)/180);
line(x1,y1,x2,y2);
x1=x2;
y1=y2;
}
}
void recur_draw(int x,int y,int k){
int x1,y1,i;
int degree=30;
int COLOR=1;
count=count+1;
setfillstyle(SOLID_FILL,COLOR);
floodfill(x-1,y+1,WHITE);
if(COLOR==1 && count==2)
printf("1. %s\n",name[0]);
for(i=1;i<k;i++){
x1=x+1.732*SIDE*cos((degree*PI)/180);
y1=y+1.732*SIDE*sin((degree*PI)/180);
draw_hexagon(x1,y1);
if(COLOR==i && count==2)
printf("%d. %s\n",i+1,name[i]);
COLOR=COLOR+1;
setfillstyle(SOLID_FILL,COLOR);
floodfill(x1-1,y1+1,WHITE);
degree=degree+60;
}
}
void frequency(int f,int k){
int x1,y1,i;
int degree=3.2+(k-3)*1.75;
int D=1.732*sqrt(k)*SIDE;
int p=f/k;
for(i=1;i<p;i++){
x1=X+D*cos((degree*PI)/180);
y1=Y+D*sin((degree*PI)/180);
draw_hexagon(x1,y1);
recur_draw(x1,y1,k);
degree=degree+60;
}
}

Sunday, November 3, 2013

Implementation of Code Division Multiple Access in Mobile Computing using C

#include<stdio.h>

#define max_user 10
#define max_data_length 20
#define max_sig_length 20

int no_user=0,no_sig_bit=0,no_data_bit=0;
int sig_seq[max_user][max_sig_length];
int z[max_data_length][max_sig_length];
int data_stream[max_user][max_data_length];

void sender();
void receiver();

void main(){
    FILE *f = fopen("CDMA.txt", "w");
    if (f == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }
    sender(f);
    receiver(f);
    fclose(f);
}
void sender(FILE *f){
    int i,j;
    int n=0;
    printf("===========================================================\n");
    printf("    Input Required Information                   \n");   
    printf("===========================================================\n");   
    fprintf(f,"===========================================================\n");
    fprintf(f,"            SENDER                    \n");   
    fprintf(f,"===========================================================\n");   
    printf("Enter number of user (<=%d)  ",max_user);       
    scanf("%d",&no_user);
    printf("Enter number of data bit (<=%d)  ",max_data_length);       
    scanf("%d",&no_data_bit);
    printf("Enter number of signature bit (<=%d)  ",max_sig_length);       
    scanf("%d",&no_sig_bit);
    printf("----------------------------------------------------\n");
    /* User */
    for(i=0;i<no_user;i++){
        printf("Enter data for User %d\n",i+1);       
        /* Data Stream */
        printf("Enter the Data Stream bit (+1 | -1)\n");       
        for(j=0;j<no_data_bit;j++){
            scanf("%d",&n);
            if(n==1 || n==-1)
                data_stream[i][j]=n;
            else{
                printf("Wrong data bit, Re-Enter\n");
                j--;
            }
        }       
        /* Signature Code */
        printf("Enter the Signature Code (+1 | -1)\n");       
        for(j=0;j<no_sig_bit;j++){
            scanf("%d",&n);
            if(n==1 || n==-1)
                sig_seq[i][j]=n;
            else{
                printf("Wrong Signature bit, Re-Enter\n");
                j--;
            }
        }
    }
    for(i=0;i<no_user;i++){
        fprintf(f,"\nSender %d\n",i+1);       
        fprintf(f,"---------------------\n");
        fprintf(f,"Data Stream:   ");
        for(j=0;j<no_data_bit;j++)
                fprintf(f,"%d ",data_stream[i][j]);
        fprintf(f,"\n");       
        fprintf(f,"Signature Sequence:   ");   
        for(j=0;j<no_sig_bit;j++)
                fprintf(f,"%d ",sig_seq[i][j]);
        fprintf(f,"\n");
    }
    fprintf(f,"_________________________________________________\n");
    /* Encoding */
    fprintf(f,"Encoded Data:\n");
    fprintf(f,"---------------------\n");
    for(i=0;i<no_data_bit;i++){
        fprintf(f,"|");
        for(j=0;j<no_sig_bit;j++){
            n=0;
            while(n<no_user){
                z[i][j]=z[i][j]+data_stream[n][i]*sig_seq[n][j];
                n++;
            }
            // Channel Output
            fprintf(f,"%d ",z[i][j]);
        }
        fprintf(f,"|");
    }
    fprintf(f,"\n");
}
void receiver(FILE *f){
    int i,j;
    int n=0,sum=0;
    fprintf(f,"===========================================================\n");
    fprintf(f,"            RECEIVER                    \n");   
    fprintf(f,"===========================================================\n");
    /* Decoding */   
    fprintf(f,"\nReceived Channel Output:\n");
    fprintf(f,"-----------------------------\n");
    for(i=0;i<no_data_bit;i++){
        fprintf(f,"|");
        for(j=0;j<no_sig_bit;j++)
            fprintf(f,"%d ",z[i][j]);
        fprintf(f,"|");
    }
    fprintf(f,"\n");
    fprintf(f,"\nSignature Code to be used:\n");
    fprintf(f,"-----------------------------\n");
    for(i=0;i<no_user;i++){
        fprintf(f,"User %d: ",i+1);
        for(j=0;j<no_sig_bit;j++)
            fprintf(f,"%d ",sig_seq[i][j]);
        fprintf(f,"\n");
    }
    fprintf(f,"\nDecoded data stream:\n");
    fprintf(f,"--------------------------------\n");
    while(n<no_user){
        fprintf(f,"\nReceiver %d\n",n+1);       
        fprintf(f,"---------------------\n");
        fprintf(f,"Data Stream: ");
        for(i=0;i<no_data_bit;i++){
            sum=0;
            for(j=0;j<no_sig_bit;j++)
                sum=sum+z[i][j]*sig_seq[n][j];       
            data_stream[n][i]=sum/no_sig_bit;
            fprintf(f,"%d ",data_stream[n][i]);
        }
        fprintf(f,"\n");
        n++;       
    }   
}

Thursday, December 13, 2012

Travelling Salesperson Problem using Genetic Algorithm in MATLAB


tsp.m

clc;
clear all;
close all;
%===========================================
number_of_cities=10;
area_size=10;
population_size=500;
number_of_generation=1000;
probability_of_mutation=0.08;
%===========================================
randomly_distribute_cities=importdata('tsp1.txt');%area_size*rand(2,number_of_cities);
distance_matrix=zeros(number_of_cities,number_of_cities);
%===========================================
%DISTANCE/COST MATRIX EVALUATION
%===========================================
for i=1:number_of_cities-1
    r1=randomly_distribute_cities(:,i);
    for j=i+1:number_of_cities
        r2=randomly_distribute_cities(:,j);
        dr=r1-r2;
        dr2=dr'*dr;
        drl=sqrt(dr2);
        distance_matrix(i,j)=drl;
        distance_matrix(j,i)=drl;
    end
end
%===========================================
% START FROM RANDOM CLOSED PATHES
% Chromosome(k,:) :- CHROMOSOME OF k-PATH
%===========================================
Chromosome=zeros(population_size,number_of_cities);
for k=1:population_size
    %for i=1:population_size
    Chromosome(k,:)=randperm(number_of_cities);%
    %Chromosome = importdata('tsp.txt');
    %display(Chromosome);
    %end
end
%===========================================
figure('units','centimeters','position',[5 2 30 15]);
subplot(1,2,1);
%===========================================
% TO PLOT BEST PATH
%===========================================
plot_of_line_btwn_2_cities=plot(NaN,NaN,'blue--');
%plot_of_line_btwn_cities=plot(NaN,NaN,'blue--');
Head_Title=title(' ');
hold on;
%===========================================
% PLOT NODES NUMBERS
%===========================================
for n=1:number_of_cities
    text(randomly_distribute_cities(1,n),randomly_distribute_cities(2,n),num2str(n),'color','black');
    plot(randomly_distribute_cities(1,n),randomly_distribute_cities(2,n),'rs','MarkerEdgeColor','green','MarkerFaceColor','red','MarkerSize',4);
end
axis equal;
xlim([-0.1*area_size 1.1*area_size]);
ylim([-0.1*area_size 1.1*area_size]);
%===========================================
path_lengths=zeros(population_size,1);
avg=zeros(number_of_generation,1);
g=zeros(number_of_generation,1);
probabilities=zeros(population_size,1);
%===========================================
% GENERATIONS LOOP
%===========================================
subplot(1,2,2);
for generation=1:number_of_generation
    g(generation,1)=generation;
    path=0;
    %-------------------------------------------
    % FIND PATHS LENGTH
    %-------------------------------------------
    for k=1:population_size
     
        individual_Chromosome=Chromosome(k,:);
        path_length_summation=0;
        for p=1:number_of_cities-1
            path_length_summation=path_length_summation+distance_matrix(individual_Chromosome(p),individual_Chromosome(p+1));
        end
        %-------------------------------------------
        % LAST AND FAST
        %-------------------------------------------
        path_length_summation=path_length_summation+distance_matrix(individual_Chromosome(number_of_cities),individual_Chromosome(1));
        path_lengths(k)=path_length_summation;
        path=path + path_length_summation;
        avg(generation,1)=path/population_size;  
    end
    %set(plot_of_line_btwn_cities,'Xdata',generation,'YData',avg);
    plot(g,avg,'r*');
 
    %-------------------------------------------
    % FIND THE PROBABILITY OF EACH CHROMOSOME
    %-------------------------------------------
    inverse_path_lengths=1./path_lengths;
    probabilities=inverse_path_lengths/sum(inverse_path_lengths);
    %-------------------------------------------
    % FIND BEST PATH
    %-------------------------------------------
    [x y]=max(probabilities);
    best_path=Chromosome(y,:);
 
    %-------------------------------------------
    % UPDATE BEST PATH ON FIGURE
    %-------------------------------------------
    if mod(generation,5)==0
        set(plot_of_line_btwn_2_cities,'Xdata',[randomly_distribute_cities(1,best_path) randomly_distribute_cities(1,best_path(1))],'YData',[randomly_distribute_cities(2,best_path) randomly_distribute_cities(2,best_path(1))]);
        set(Head_Title,'string',['Generation: ' num2str(generation)  '  Best Path Length: ' num2str(path_lengths(y))]);
        drawnow;
    end
    %-------------------------------------------
    % SELECTION
    %-------------------------------------------
    index=roulette_wheel(population_size,probabilities);
    %-------------------------------------------
    % CHROMOSOME'S TO CROSSOVER
    %-------------------------------------------
    Chromosome_Crossover=Chromosome(index,:);
    Chromosome_Children=zeros(population_size,number_of_cities);
    for prc=1:(population_size/2)
        i1=1+2*(prc-1);
        i2=2+2*(prc-1);
        Chromosome1=Chromosome_Crossover(i1,:);
        Chromosome2=Chromosome_Crossover(i2,:);
        Crossover_Point=ceil((number_of_cities-1)*rand);
        % TWO CHILDREN'S
        Chromosome1_Children=PMX(Chromosome1,Chromosome2,Crossover_Point);
        Chromosome2_Children=PMX(Chromosome2,Chromosome1,Crossover_Point);
        Chromosome_Children(i1,:)=Chromosome1_Children;
        Chromosome_Children(i2,:)=Chromosome2_Children;
    end
    Chromosome=Chromosome_Children;
 
    %-------------------------------------------
    % MUTATION(Interchanging)
    %-------------------------------------------
    for k=1:population_size
        if rand<probability_of_mutation
            % Expected probability of a mutation of one individual is no.of cities * probability_of_mutation)
            i=ceil(number_of_cities*rand);
            j=ceil(number_of_cities*rand);
            Chromosome(k,i:j)=fliplr(Chromosome(k,i:j));
        end
    end
    Chromosome(1,:)=best_path; % elitism    
end
display(best_path);

roulette_wheel.m


function index=roulette_wheel(population_size,probabilities)

cummulative_sum_of_probabilities=cumsum(probabilities);
n=length(probabilities);
sz=size(cummulative_sum_of_probabilities);
if sz(1)>sz(2)
    cpr1=cummulative_sum_of_probabilities';
else
    cpr1=cummulative_sum_of_probabilities;
end
%===========================================
% RANDOM NUMBERS FROM 1:n ACCORDING PROBABILITIES
%===========================================
index1=interp1([0 cpr1],1:(n+1),rand(1,population_size),'linear');
index=floor(index1);

PMX.m


function Chromosome_Children=PMX(Chromosome1,Chromosome2,Crossover_Point)

for i=1:Crossover_Point
    if Chromosome2(i)~=Chromosome1(i)
        ind=find(Chromosome1==Chromosome2(i));
        %swap
        Chromosome1(ind)=Chromosome1(i);
        Chromosome1(i)=Chromosome2(i);
    end
end
Chromosome_Children=Chromosome1;

tsp1.txt


1 2 3 4 5 6 7 8 9 10
10 9 2 3 1 4 5 6 7 8



Monday, December 5, 2011

Apply Different Textures to Torus






#include <stdlib.h>
#include <math.h>
#include <limits.h>

#include <GL/glut.h>               
const float PI2 = 2.0f*3.1415926535;

GLenum runMode = GL_TRUE;

GLenum shadeModel = GL_FLAT;       
GLenum polygonMode = GL_LINE;       


float RotX = 0.0f;           
float RotY=0.0f;
float RotIncrementX = 0.0;
float RotIncrementY = 0.0;
const float RotIncFactor = 1.5;


int NumWraps = 10;
int NumPerWrap = 8;


float MajorRadius = 3.0;
float MinorRadius = 1.0;


int QuadMode = 1;       
GLenum LocalMode = GL_TRUE;   
int Light0Flag = 1;       
int Light1Flag = 1;       
int Light2Flag = 1;


float ambientLight[4] = {0.0, 1.0, 0.0, 1.0};
float Lt0amb[4] = {0.0, 0.0, 1.0, 1.0};
float Lt0diff[4] = {0.0, 1.0, 1.0, 1.0};
float Lt0spec[4] = {1.0, 1.0, 1.0, 1.0};
float Lt0pos[4] = {1.7*(3.0+1.0), 0.0, 0.0, 1.0};

float Lt1amb[4] = {1.0, 1.0, 0.0, 1.0};
float Lt1diff[4] = {1.0, 0.0, 1.0, 1.0};
float Lt1spec[4] = {1.0, 1.0, 0.0, 1.0};
float Lt1pos[4] = {0.0, 1.2*(3.0+1.0), 0.0, 1.0};

float Lt2amb[4] = {0.0, 1.0, 1.0, 1.0};
float Lt2diff[4] = {1.0, 1.0, 0.0, 1.0};
float Lt2spec[4] = {1.0, 0.0, 1.0, 1.0};
float Lt2pos[4] = {1.0,1.0*(3.0+1.0), 0.0, 1.0};

float Noemit[4] = {0.0, 0.0, 0.0, 1.0};
float Matspec[4] = {0.3, 0.3, 0.3, 1.0};
float Matnonspec[4] = {0.4, 0.4, 0.4, 1.0};
float Matshiny = 16.0;

// A texture
int TextureWrapVert=6;
int TextureWrapHoriz=6;
int textureFlag = 1;

#define    stripeImageWidth 32
GLubyte stripeImage[4*stripeImageWidth];

#ifdef GL_VERSION_1_1
static GLuint texName;
#endif


void makeStripeImage(void)
{
   int j;
   
   for (j = 0; j < stripeImageWidth; j++) {
      stripeImage[4*j] = (GLubyte) ((j<=4) ? 255 : 0);
      stripeImage[4*j+1] = (GLubyte) ((j>4) ? 255 : 0);
      stripeImage[4*j+2] = (GLubyte) 0;
      stripeImage[4*j+3] = (GLubyte) 255;
   }
}

static GLfloat xequalzero[] = {1.0, 0.0, 0.0, 0.0};
static GLfloat slanted[] = {1.0, 1.0, 1.0, 0.0};
static GLfloat *currentCoeff;
static GLenum currentPlane;
static GLint currentGenMode;

void ResetAnimation() {
    RotX = RotY = RotIncrementX = RotIncrementY = 0.0;
}


void ZeroRotation() {
    RotIncrementX = RotIncrementY = 0.0;
}


void ShadeModelToggle() {
    if ( shadeModel == GL_FLAT ) {
        shadeModel = GL_SMOOTH;
    }
    else {
        shadeModel = GL_FLAT;
    }
}


void FillModeToggle() {
    if ( polygonMode == GL_LINE ) {
        polygonMode = GL_FILL;
    }
    else {
        polygonMode = GL_LINE;
    }
}


void QuadTriangleToggle() {
    QuadMode = 1-QuadMode;
}


void LocalToggle() {
    LocalMode = !LocalMode;
    if ( LocalMode ) {
        Lt0pos[3] = Lt1pos[3] = 1.0;   
    }
    else {
        Lt0pos[3] = Lt1pos[3] = 0.0;   
    }
}


void Light0Toggle() {
    Light0Flag = 1-Light0Flag;
}

void Light1Toggle() {
    Light1Flag = 1-Light1Flag;
}

void Light2Toggle() {
    Light2Flag = 1-Light2Flag;
}



void WrapMore() {
    NumWraps++;
}


void WrapLess() {
    if (NumWraps>4) {
        NumWraps--;
    }
}


void NumPerWrapMore() {
    NumPerWrap++;   
}

// Decrement number segments per wrap
void NumPerWrapLess() {
    if (NumPerWrap>4) {
        NumPerWrap--;
    }
}
void putVertTexture(int i, int j) {
    float wrapFrac = (j%NumPerWrap)/(float)NumPerWrap;
    float wrapFracTex = (float)j/(float)NumPerWrap;
    float phi = PI2*wrapFrac;
    float thetaFrac = ((float)(i%NumWraps)+wrapFracTex)/(float)NumWraps;
    float thetaFracTex = ((float)i+wrapFracTex)/(float)NumWraps;
    float theta = PI2*thetaFrac;
    float sinphi = sin(phi);
    float cosphi = cos(phi);
    float sintheta = sin(theta);
    float costheta = cos(theta);
    float y = MinorRadius*sinphi;
    float r = MajorRadius + MinorRadius*cosphi;
    float x = sintheta*r;
    float z = costheta*r;

    glTexCoord2f( wrapFracTex*(float)TextureWrapVert, thetaFracTex*(float)TextureWrapHoriz );
    glNormal3f(sintheta*cosphi, sinphi, costheta*cosphi);
    glVertex3f(x,y,z);
}

int i,j;
void updateScene( void )
{


    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glShadeModel( shadeModel );   
    glPolygonMode(GL_FRONT_AND_BACK, polygonMode);   
    glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, LocalMode);


    glDisable( GL_TEXTURE_2D );
    if ( Light0Flag==1 || Light1Flag==1 ) {
       
        glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Noemit);
        glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Noemit);
        glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50.0);
    }
    if ( Light0Flag==1 ) {
        glPushMatrix();
        glTranslatef(Lt0pos[0], Lt0pos[1], Lt0pos[2]);
        glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Lt0diff);
        glutSolidSphere(0.5,5,5);
        glPopMatrix();
        glEnable(GL_LIGHT0);
        glLightfv(GL_LIGHT0, GL_POSITION, Lt0pos);
    }
    else {
        glDisable(GL_LIGHT0);
    }
    if ( Light1Flag==1 ) {
        glPushMatrix();
        glTranslatef(Lt1pos[0], Lt1pos[1], Lt1pos[2]);
        glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Lt1diff);
        glutSolidSphere(0.3,5,5);
        glPopMatrix();
        glEnable(GL_LIGHT1);
        glLightfv(GL_LIGHT1, GL_POSITION, Lt1pos);
    }
    else {
        glDisable(GL_LIGHT1);
    }

    // Torus Materials
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Matnonspec);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Matspec);
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, Matshiny);
    glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Noemit);

    if ( textureFlag ) {
        glEnable( GL_TEXTURE_2D );
    }

    glPushMatrix();       

    // Update the orientation of the torus, if the animation is running.
    if ( runMode ) {
        RotY += RotIncrementY;
        if ( fabs(RotY)>360.0 ) {
            RotY -= 360.0*((int)(RotY/360.0));
        }
        RotX += RotIncrementX;
        if ( fabs(RotX)>360.0 ) {
            RotX -= 360.0*((int)(RotX/360.0));
        }
    }
    // Set the orientation.
    glRotatef( RotX, 1.0, 0.0, 0.0);
    glRotatef( RotY, 0.0, 1.0, 0.0);

    // Draw the torus
    for (i=0; i<NumWraps; i++ ) {
        glBegin( QuadMode ? GL_QUAD_STRIP : GL_TRIANGLE_STRIP);
        for ( j=0; j<=NumPerWrap; j++) {
            putVertTexture(i, j);
            putVertTexture(i+1,j);
        }
        glEnd();
    }

    // Draw a reference sphere
    glDisable( GL_TEXTURE_2D );
    glTranslatef( -MajorRadius-MinorRadius-0.3, 0.0, 0.0);
    glColor3f( 1.0f, 0.0f, 0.0f );
    glutWireSphere( 0.2f, 5, 5 );

    glPopMatrix();       

#ifdef GL_VERSION_1_1
   glBindTexture(GL_TEXTURE_1D, texName);
#endif
    glFlush();
    glutSwapBuffers();
}

void myKeyboardFunc( unsigned char key, int x, int y )
{
    switch ( key ) {
    case 'a':
        runMode = !runMode;
        break;
    case 's':
        runMode = GL_TRUE;
        updateScene();
        runMode = GL_FALSE;
        break;
    case 'e':   
        exit(1);
    case 'r':    // Reset the animation (resets everything)
        ResetAnimation();
        break;
    case 'z':    // Zero the rotation rates
        ZeroRotation();
        break;
    case 'f':    // Shade mode toggles from flat to smooth
        ShadeModelToggle();
        break;
    case 'p':    // Polygon mode toggles between fill and line
        FillModeToggle();
        break;
    case 'w':    // Decrement number of wraps around torus
        WrapLess();
        break;
    case 'W':    // Increment number of wraps around torus
        WrapMore();
        break;
    case 'n':    // Decrement number of polys per wrap
        NumPerWrapLess();
        break;
    case 'N':    // Increment number of polys per wrap
        NumPerWrapMore();
        break;
    case 'q':    // Toggle between triangles and Quadrilaterals
        QuadTriangleToggle();
        break;
    case 'l':    // Toggle between local and non-local viewer
        LocalToggle();
        break;
    case '0':    // Toggle light #0 on and off
        Light0Toggle();
        break;
    case '1':    // Toggle light #1 on and off
        Light1Toggle();
        break;
    case '2':    // Toggle light #2 on and off
        Light2Toggle();
        break;
    case 't':
        textureFlag = !textureFlag;
        break;       
    }
}
void KeyUp() {
    if ( RotIncrementX == 0.0 ) {
        RotIncrementX = -0.1;       
    }
    else if ( RotIncrementX < 0.0f) {
        RotIncrementX *= RotIncFactor;
    }
    else {
        RotIncrementX /= RotIncFactor;
    }   
}

void KeyDown() {
    if ( RotIncrementX == 0.0 ) {
        RotIncrementX = 0.1;       
    }
    else if ( RotIncrementX > 0.0f) {
        RotIncrementX *= RotIncFactor;
    }
    else {
        RotIncrementX /= RotIncFactor;
    }   
}

void KeyLeft() {
    if ( RotIncrementY == 0.0 ) {
        RotIncrementY = -0.1;       
    }
    else if ( RotIncrementY < 0.0) {
        RotIncrementY *= RotIncFactor;
    }
    else {
        RotIncrementY /= RotIncFactor;
    }   
}

void KeyRight()
{
    if ( RotIncrementY == 0.0 ) {
        RotIncrementY = 0.1;       
    }
    else if ( RotIncrementY > 0.0) {
        RotIncrementY *= RotIncFactor;
    }
    else {
        RotIncrementY /= RotIncFactor;
    }   
}



void mySpecialKeyFunc( int key, int x, int y )
{
    switch ( key ) {
    case GLUT_KEY_UP:       

        KeyUp();
        break;
    case GLUT_KEY_DOWN:

        KeyDown();
        break;
    case GLUT_KEY_LEFT:

        KeyLeft();
        break;
    case GLUT_KEY_RIGHT:

        KeyRight();
        break;
    }
}


void initRendering()
{
    glEnable( GL_DEPTH_TEST );

    glEnable(GL_LIGHTING);       
    glEnable(GL_LIGHT0);       
    glEnable(GL_LIGHT1);
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight);

    // Light 0 (Position is set in updateScene)
    glLightfv(GL_LIGHT0, GL_AMBIENT, Lt0amb);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, Lt0diff);
    glLightfv(GL_LIGHT0, GL_SPECULAR, Lt0spec);

    // Light 1 (Position is set in updateScene)
    glLightfv(GL_LIGHT1, GL_AMBIENT, Lt1amb);
    glLightfv(GL_LIGHT1, GL_DIFFUSE, Lt1diff);
    glLightfv(GL_LIGHT1, GL_SPECULAR, Lt1spec);
    // Light 2 (Position is set in updateScene)
    glLightfv(GL_LIGHT1, GL_AMBIENT, Lt2amb);
    glLightfv(GL_LIGHT1, GL_DIFFUSE, Lt2diff);
    glLightfv(GL_LIGHT1, GL_SPECULAR, Lt2spec);

    // Load the texture
   makeStripeImage();
   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

#ifdef GL_VERSION_1_1
   glGenTextures(1, &texName);
   glBindTexture(GL_TEXTURE_1D, texName);
#endif
   glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
   glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
#ifdef GL_VERSION_1_1
   glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, stripeImageWidth, 0,
                GL_RGBA, GL_UNSIGNED_BYTE, stripeImage);
#else
   glTexImage1D(GL_TEXTURE_1D, 0, 4, stripeImageWidth, 0,
                GL_RGBA, GL_UNSIGNED_BYTE, stripeImage);
#endif

   glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
   currentCoeff = xequalzero;
   currentGenMode = GL_OBJECT_LINEAR;
   currentPlane = GL_OBJECT_PLANE;
   glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, currentGenMode);
   glTexGenfv(GL_S, currentPlane, currentCoeff);

   glEnable(GL_TEXTURE_GEN_S);
   glEnable(GL_TEXTURE_1D);
    //glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
}


void resizeWindow(int w, int h)
{
    float aspectRatio;
    glViewport( 0, 0, w, h );   
    h = (w == 0) ? 1 : h;
    aspectRatio = (float)w/(float)h;

   
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective( 60.0, aspectRatio, 1.0, 30.0 );


    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glTranslatef(0.0, 0.0, -10.0);
    glRotatef(25.0, 1.0,0.0,0.0);   
}



int main( int argc, char** argv )
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );

    glutInitWindowPosition( 10, 60 );
    glutInitWindowSize( 1200, 1400 );
    glutCreateWindow( "TextureTorus" );

    initRendering();
    resizeWindow(1200,1400);

   
    glutKeyboardFunc( myKeyboardFunc );
    glutSpecialFunc( mySpecialKeyFunc );

   
    glutReshapeFunc( resizeWindow );

   
    glutIdleFunc( updateScene );
   
    glutDisplayFunc( updateScene );
   
   
    glutMainLoop(  );

    return(0);   
}

Draw a Wireframe model of sphere in OpenGL. Perform Backface Culling of polygon away from viewer



#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>

GLfloat tdist = 0.0;

enum {FILL, WIRE, BACKFACE};

int rendermode = FILL;

void menu(int selection)
{
  rendermode = selection;
  glutPostRedisplay();
}


/* geometry display list names */
enum {SPHERE = 1,FLOOR, WALLS};

void drawscene(void)
{
GLfloat i;   
    glPushMatrix();

    glTranslatef(10.f, -10.f, -400.f);
    //glRotatef(-10.0, 1.0, 0.0, 0.0);
  glRotatef(30.0, 1.0, 0.0, 0.0);
    glCallList(SPHERE);
    glPopMatrix();

   
}

void redraw(void)
{
  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);

  switch(rendermode) {
  case FILL:
    drawscene();
    break;
  case WIRE: /* basic wireframe mode */
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    drawscene();
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    break;
  case BACKFACE: /* use backface culling to clean things up */
    glEnable(GL_CULL_FACE);
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    drawscene();
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    glDisable(GL_CULL_FACE);
    break;
 
  }

   
    glFlush();
}

void key(unsigned char key, int x, int y)
{
    switch (key) {
      case 't':
         if (tdist < 140.0) {
            tdist = (tdist + 0.5);
            glutPostRedisplay();
         }
         break;
      case 'T':
         if (tdist > -50.0) {
            tdist = (tdist - 0.5);
            glutPostRedisplay();
         }
         break;
    case 'e':
        exit(0);
    }
}
main(int argc, char *argv[])
{



    GLfloat *tex;
    static GLfloat lightpos[] = {-50.f, -50.f, -320.f, 1.f};
    static GLfloat sphere_mat[] = {0.0, 1.0, 1.0, 1.0};
  
    GLUquadricObj *sphere;

    glutInit(&argc, argv);
    glutInitWindowSize(700, 700);
    glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_STENCIL);
    (void)glutCreateWindow("Wireframe_Backface");
   
    glutDisplayFunc(redraw);
    glutKeyboardFunc(key);

    glutCreateMenu(menu);
    glutAddMenuEntry("Solid Fill", FILL);
    glutAddMenuEntry("Wireframe", WIRE);
    glutAddMenuEntry("Backface Culling", BACKFACE);
 
    glutAttachMenu(GLUT_RIGHT_BUTTON);


    /* draw a perspective scene */
    glMatrixMode(GL_PROJECTION);
    glFrustum(-100., 100., -100., 100., 320., 640.);
    glMatrixMode(GL_MODELVIEW);

   
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glClearColor(1.0, 0.0, 0.0, 1.0);

  
    glLightfv(GL_LIGHT0, GL_POSITION, lightpos);

   
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glNewList(SPHERE, GL_COMPILE);

    glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, sphere_mat);
    glutSolidSphere (80, 50, 50);
    glEndList();
 
    glutMainLoop();
    return 0;            
}

Render a scene containing three subject(overlapping each other) i.e. Torus,Teapot and sphere in opengl.

#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>

void display() {
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  GLfloat black[] = { 0.0, 0.0, 0.0, 1.0 };
  GLfloat red[] = { 1.0, 0.0, 0.0, 1.0 };
  GLfloat cyan[] = { 0.0, 1.0, 1.0, 1.0 };
  GLfloat white[] = { 1.0, 1.0, 1.0, 1.0 };
  GLfloat direction[] = { 1.0, 1.0, 1.0, 0.0 };

  glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, cyan);
  glMaterialfv(GL_FRONT, GL_SPECULAR, white);
  glMaterialf(GL_FRONT, GL_SHININESS, 50);

  glLightfv(GL_LIGHT0, GL_AMBIENT, black);
  glLightfv(GL_LIGHT0, GL_DIFFUSE, red);
  glLightfv(GL_LIGHT0, GL_SPECULAR, white);
  glLightfv(GL_LIGHT0, GL_POSITION, direction);

  glEnable(GL_LIGHTING);               
  glEnable(GL_LIGHT0);                 
  glEnable(GL_DEPTH_TEST);             

 

// Add a torus to the scene.
  glPushMatrix();
    glRotatef(-20.0, 1.0, 0.0, 0.0);
  glRotatef(90.0, 1.0, 0.0, 0.0);
  glutSolidTorus(0.275, 0.85, 16, 40);
  glPopMatrix();

GLfloat blue1[] = { 0.0, 0.0, 1.0, 1.0 };
  GLfloat magenta1[] = { 1.0, 0.0, 1.0, 1.0 };
  GLfloat red1[] = { 1.0, 0.0, 0.0, 1.0 };
  GLfloat yellow1[] = { 1.0, 1.0, 0.0, 1.0 };
  GLfloat direction2[] = { 1.0, 1.0, 1.0, 0.0 };

  glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red1);
  glMaterialfv(GL_FRONT, GL_SPECULAR, yellow1);
  glMaterialf(GL_FRONT, GL_SHININESS, 50);

  glLightfv(GL_LIGHT0, GL_AMBIENT, blue1);
  glLightfv(GL_LIGHT0, GL_DIFFUSE, magenta1);
  glLightfv(GL_LIGHT0, GL_SPECULAR, yellow1);
  glLightfv(GL_LIGHT0, GL_POSITION, direction2);

  glEnable(GL_LIGHTING);               
  glEnable(GL_LIGHT0);                 
  glEnable(GL_DEPTH_TEST);             
  // Add a teapot to the scene.
  glPushMatrix();
  glTranslatef(0.75, -0.5, 0.0);
  glRotatef(45.0, 1.0, 0.0, 0.0);
  glutSolidTeapot(1);
  glPopMatrix();

  GLfloat blue[] = { 0.0, 0.0, 1.0, 1.0 };
  GLfloat magenta[] = { 1.0, 0.0, 1.0, 1.0 };
  GLfloat green[] = { 0.0, 1.0, 0.0, 1.0 };
  GLfloat yellow[] = { 1.0, 1.0, 0.0, 1.0 };
  GLfloat direction1[] = { 1.0, 1.0, 1.0, 0.0 };

  glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green);
  glMaterialfv(GL_FRONT, GL_SPECULAR, yellow);
  glMaterialf(GL_FRONT, GL_SHININESS, 50);

  glLightfv(GL_LIGHT0, GL_AMBIENT, blue);
  glLightfv(GL_LIGHT0, GL_DIFFUSE, magenta);
  glLightfv(GL_LIGHT0, GL_SPECULAR, yellow);
  glLightfv(GL_LIGHT0, GL_POSITION, direction1);

  glEnable(GL_LIGHTING);               
  glEnable(GL_LIGHT0);                 
  glEnable(GL_DEPTH_TEST);             
  // Add a sphere to the scene.
  glPushMatrix();
  glTranslatef(0.75, 0.0, -1.0);
  glutSolidSphere(1.0, 30, 30);
  glPopMatrix();

  glPopMatrix();
  glFlush();
}


void reshape(GLint w, GLint h) {
 glViewport(0,0,(GLsizei)w,(GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(30, (GLfloat)w/(GLfloat)h,1.0,100.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0);
}




int main(int argc, char** argv) {
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
  glutInitWindowPosition(80, 80);
  glutInitWindowSize(800, 600);
  glutCreateWindow("Hidden Surface");
  glutReshapeFunc(reshape);
  glutDisplayFunc(display);
  glutMainLoop();
}

Monday, January 17, 2011

Histogram

 filewrite.c
#include<stdio.h>
main()
{
    FILE *f=fopen("Number.dat","w");
    int a[8],i;
    for(i=0;i<8;i++)
    {
        printf("a[%d]=",i);           
        scanf("%d",&a[i]);
    }
    fwrite(a,sizeof(int),8,f);
    fclose(f);
}


Compile: cc filewrite.c
   Run    : ./a.out

 Histogram.c
#include<stdio.h>
main(int argc,char *argv[])
{
    int a[8],j,i,count[20],flag=0;
    FILE *f=fopen(argv[1],"r");
    fread(a,sizeof(int),8,f);
    for(i=0;i<8;i++)
    {
        count[i]=0;
        for(j=0;j<8;j++)
        {
            if(a[i]==a[j])
            count[i]++;
        }
        flag=0;
        for(j=0;j<=i;j++)
        {
            if((a[i]==a[j])&& (i!=j))
            flag=1;
        }
        if(!flag)
        {
            printf("\n%d\t",a[i]);
            for(j=0;j<count[i];j++)
            printf("*");
        }
    }
    printf("\n");
    fclose(f);
}


Compile: cc Histogram.c
      Run: ./a.out Number.dat