0% found this document useful (0 votes)
3 views

MAT LAB Record Final

The document is a practical record for the M.Sc. Computer Science program at Muthurangam Government Arts College, detailing various MATLAB exercises for the academic year 2024-2025. It includes sections on array functions, vector manipulation, matrix operations, and 2D plotting techniques such as pie charts and histograms. Each exercise outlines the aim, description, MATLAB program, output, and results of the implemented tasks.

Uploaded by

subapalani2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

MAT LAB Record Final

The document is a practical record for the M.Sc. Computer Science program at Muthurangam Government Arts College, detailing various MATLAB exercises for the academic year 2024-2025. It includes sections on array functions, vector manipulation, matrix operations, and 2D plotting techniques such as pie charts and histograms. Each exercise outlines the aim, description, MATLAB program, output, and results of the implemented tasks.

Uploaded by

subapalani2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

MUTHURANGAM GOVERNMENT

ARTS COLLEGE(AUTONOMOUS)
VELLORE-2
PG & Research Department of Computer Science
M.Sc., COMPUTER SCIENCE

PRACTICAL RECORD
2024-2025

REG.NO : ……………………………. NAME :…………………………………………

SUB.CODE : …………………………………………………………………………………

SUBJECT : ………………………………………………………………………………….

CLASS :………………………………………………………………………………….
MUTHURANGAM GOVERNMENT

ARTS COLLEGE (AUTONOMOUS)


VELLORE-2

PG & Research Department of Computer Science


M.Sc., COMPUTER SCIENCE

BONAFIDE CERTIFICATE

Certified to be a bonafide record of work done by ....................................................

(Reg.No……………………………….) in the Laboratory of this College, submitted

for...……………. Semester Practical Examination in ………………………………… during the

Academic Year …………………......

Staff In-charge Head of the Department

Submitted for the Practical Examination held on ………………………

Internal Examiner External Examiner


INDEX

SI. PAGE
DATE TITLE SIGN
NO. NO.

1. ARRAY FUNCTION

2. VECTOR MANIPULATION

3. MATRIX MANIPULATION OPERATIONS

TWO-DIMENSIONAL PLOTTING

4. PIE CHART AND HISTOGRAM

5. TRIGONOMETRIC FUNCTIONS

6. SINE WAVE

THREE-DIMENSIONAL PLOTTING

7. SURFACE PLOT FUNCTION

8. MESH PLOT FUNCTION

9. INTERPOLATION OF SCATTERED DATA

10. SIMPLE CALCULATOR USING GUI


Ex. No: 01
ARRAY FUNCTION
Date:

AIM

To Implement the MAT LAB built-in array functions for creating zero, one, and identity
matrices and retrieving array dimensions.

DESCRIPTION

zeros(n) Creates a n x n matrix of zeros.

zeros(m,n) Creates a m x n matrix of zeros

zeros(size(arr)) Create a matrix of zeros of the same size as arr.

ones(n) Creates a n x n matrix of ones.

ones(m,n) Creates a m x n matrix of ones.

ones(size(arr)) Creates a matrix of ones of the same size as arr.

eye(n) Creates a n x n identity matrix.

eye(m,n) Creates an m x n identity matrix.

length(arr) Return the length of a vector, or the longest dimension of a 2D array.

size(arr) Return two values specifying the number of rows and columns in arr.
MATLAB PROGRAM

% MATLAB Program to Demonstrate Built-in Array Functions


arr = [1 2 3; 4 5 6; 7 8 9]; % Define a sample matrix for size reference

% Creating matrices of zeros


n = 3;
m = 2;
zeroMatrix1 = zeros(n); % n x n matrix of zeros
zeroMatrix2 = zeros(m, n); % m x n matrix of zeros
zeroMatrix3 = zeros(size(arr)); % Matrix of zeros of the same size as arr

% Creating matrices of ones


oneMatrix1 = ones(n); % n x n matrix of ones
oneMatrix2 = ones(m, n); % m x n matrix of ones
oneMatrix3 = ones(size(arr)); % Matrix of ones of the same size as arr

% Creating identity matrices


identityMatrix1 = eye(n); % n x n identity matrix
identityMatrix2 = eye(m, n); % m x n identity matrix

% Finding length and size of an array


vec = [1 2 3 4 5]; % Example vector
arrLength = length(arr); % Longest dimension of the array
vecLength = length(vec); % Length of a vector
[arrRows, arrCols] = size(arr); % Number of rows and columns in arr

% Display results
disp('Zero Matrices:');
disp(zeroMatrix1);
disp(zeroMatrix2);
disp(zeroMatrix3);

disp('One Matrices:');
disp(oneMatrix1);
disp(oneMatrix2);
disp(oneMatrix3);

disp('Identity Matrices:');
disp(identityMatrix1);
disp(identityMatrix2);

disp('Array Length and Size:');


disp(['Length of arr: ', num2str(arrLength)]);
disp(['Length of vec: ', num2str(vecLength)]);
disp(['Size of arr: ', num2str(arrRows), ' x ', num2str(arrCols)]);

OUTPUT
>> Array
Zero Matrices:
0 0 0
0 0 0
0 0 0

0 0 0
0 0 0

0 0 0
0 0 0
0 0 0
One Matrices:
1 1 1
1 1 1
1 1 1

1 1 1
1 1 1

1 1 1
1 1 1
1 1 1

Identity Matrices:
1 0 0
0 1 0
0 0 1

1 0 0
0 1 0

Array Length and Size:


Length of arr: 3
Length of vec: 5
Size of arr: 3 x 3

RESULT

The MAT LAB built-in array functions have been successfully implemented.
Ex. No: 02
VECTOR MANIPULATION
Date:

AIM

To Implement various vector operations in MATLAB, including addition, subtraction,


transpose, appending elements, dot product, cross product, and element-wise operations.

DESCRIPTION

Addition (A + B) Adds corresponding elements of two vectors.

Subtraction (A - B) Subtracts elements of B from A.

Transpose (A') Converts a row vector to a column vector.

Append ([A, value]) Adds an element to the vector.

Dot Product (dot(A, B)) Computes the sum of element-wise multiplication.

Cross Product (cross(A, B)) Computes the cross product (only for 3D vectors).

Element-wise Multiplication (A .* B) Multiplies corresponding elements.

Element-wise Division (A ./ B) Divides corresponding elements.


MATLAB PROGRAM

% Define two 5D vectors


A = [1 2 3 4 5];
B = [5 4 3 2 1];

% Define two 3D vectors for cross product demonstration


C = [1 2 3];
D = [4 5 6];

% Vector Addition
vectorSum = A + B;

% Vector Subtraction
vectorDiff = A - B;

% Vector Transpose
A_transpose = A';

% Append an element to vector A


A_appended = [A, 6];

% Dot Product
dotProduct_AB = dot(A, B);
dotProduct_CD = dot(C, D);

% Cross Product for 3D vectors


crossProduct_CD = cross(C, D);

% Element-wise Multiplication
elementWiseMult = A .* B;
% Element-wise Division
elementWiseDiv = A ./ B;

% Display results
disp('Vector A:');
disp(A);

disp('Vector B:');
disp(B);

disp('Vector Sum (A + B):');


disp(vectorSum);

disp('Vector Difference (A - B):');


disp(vectorDiff);

disp('Transpose of A:');
disp(A_transpose);

disp('Vector A after appending 6:');


disp(A_appended);

disp('Dot Product of A and B:');


disp(dotProduct_AB);

disp('Dot Product of C and D:');


disp(dotProduct_CD);

disp('Vector C:');
disp(C);
disp('Vector D:');
disp(D);

disp('Cross Product of C and D:');


disp(crossProduct_CD);

disp('Element-wise Multiplication (A .* B):');


disp(elementWiseMult);

disp('Element-wise Division (A ./ B):');


disp(elementWiseDiv);

OUTPUT
>> Vector
Vector A:
1 2 3 4 5

Vector B:
5 4 3 2 1

Vector Sum (A + B):


6 6 6 6 6

Vector Difference (A - B):


-4 -2 0 2 4

Transpose of A:
1
2
3
4
5

Vector A after appending 6:


1 2 3 4 5 6

Dot Product of A and B:


35

Dot Product of C and D:


32

Vector C:
1 2 3

Vector D:
4 5 6

Cross Product of C and D:


-3 6 -3

Element-wise Multiplication (A .* B):


5 8 9 8 5

Element-wise Division (A ./ B):


0.2000 0.5000 1.0000 2.0000 5.0000

RESULT

The MAT LAB Vector Operations has been successfully implemented.


Ex. No: 03
MATRIX MANIPULATION OPERATIONS
Date:

AIM

To Implement various Matrix manipulation operations in MATLAB, including addition,


subtraction, multiplication, Transpose and Determinant operations.

DESCRIPTION

Addition (A + B) Adds corresponding elements of matrices A and B.

Subtraction (A - B) Subtracts corresponding elements of matrices A and B.

Multiplication (A * B) Performs standard matrix multiplication.

Transpose (A') Swaps rows and columns of matrix A.

Determinant (det(A)) Computes the determinant to check if A is invertible.

Inverse (inv(A)) Computes the inverse of A if it is non-singular.


MATLAB PROGRAM

% Define two matrices A and B


A = [1 2 3; 4 5 6; 7 8 9];
B = [9 8 7; 6 5 4; 3 2 1];

disp('Matrix A:');
disp(A);

disp('Matrix B:');
disp(B);

% Matrix Addition
matrixSum = A + B;
disp('Matrix Addition (A + B):');
disp(matrixSum);

% Matrix Subtraction
matrixDiff = A - B;
disp('Matrix Subtraction (A - B):');
disp(matrixDiff);

% Matrix Multiplication
matrixProd = A * B;
disp('Matrix Multiplication (A * B):');
disp(matrixProd);

% Transpose of A
transposeA = A';
disp('Transpose of A (A''):');
disp(transposeA);
% Determinant of A
detA = det(A);
disp('Determinant of A:');
disp(detA);

OUTPUT
>> Matrix
Matrix A:
1 2 3
4 5 6
7 8 9

Matrix B:
9 8 7
6 5 4
3 2 1

Matrix Addition (A + B):


10 10 10
10 10 10
10 10 10

Matrix Subtraction (A - B):


-8 -6 -4
-2 0 2
4 6 8

Matrix Multiplication (A * B):


30 24 18
84 69 54
138 114 90

Transpose of A (A'):
1 4 7
2 5 8
3 6 9

Determinant of A:
6.6613e-16

RESULT

The Matrix manipulation operations in MATLAB, has been implemented successfully.


Ex. No: 04 TWO-DIMENSIONAL PLOTTING

Date: PIE CHART AND HISTOGRAM

AIM

To Implement 2D plot for Pie chart and Histogram using MAT LAB Procedure.

DESCRIPTION

pie(data, labels) Creates a pie chart using data and optional labels.

histogram(data, bins) Displays a histogram of data with a specified number of bins.

Divides a figure into m × n sections and places a plot in


subplot(m, n, p)
position p.

1. Two - dimensional Plots


To draw a two - dimensional plot in MATLAB, the plot command is used. The syntax is given
as follows:

plot(x, y)

where,

x is a vector containing the x - coordinates of the plot and

y is a vector containing the y - coordinates of the plot.

2. Grid

To give better illustration of the coordinates on the plot, a grid is used. The command
grid is used to show the grid lines on the plot. The grid on the plot can be added or removed
by using the on and off with the grid command. When grid command without any argument
is used alternatively, it toggles the grid drawn. By default, MATLAB starts with grid off.
3. Printing Labels

To make the plot more understandable, the two axes are labelled and a title is provided above
the top of the plot by using the following commands.

xlabel(‘string’) %Statement 1

ylabel(‘string’) %Statement 2

title(‘string’) %Statement

where, Statement 1 uses the command xlabel to print label on the x - axis. The label to be
printed is enclosed in single quotes. Similarly, Statement 2 uses the command ylabel to print
the label along y - axis. The command title in Statement 3 is used to provide a title above the
top of the graph.

PROCEDURE

1. Define the Pie Chart Data

 Create a vector representing the percentage of different categories.

 Assign labels for each category.

2. Generate Data for Histogram

 Use randi([min, max], size) to create random data.

 Choose an appropriate number of bins for the histogram.

3. Create a Figure with Subplots

 Use figure to open a new window.

 Use subplot(1,2,1) to create space for the pie chart

 Use subplot(1,2,2) for the histogram.

4. Plot the Pie Chart

 Use pie() to generate a pie chart with the defined data and labels.

 Use colormap() to apply colors.


5. Plot the Histogram

 Use histogram() to plot the frequency distribution.

 Add axis labels, titles, and grid lines for clarity.

MATLAB PROGRAM

% Sample data for the pie chart

pieData = [25, 15, 30, 10, 20]; % Percentages of different categories

pieLabels = {'A', 'B', 'C', 'D', 'E'}; % Labels for the pie chart

% Generate random data for the histogram

histData = randi([1, 100], 1, 100); % 100 random values between 1 and 100

numBins = 10; % Number of bins for histogram

% Create a figure window with two subplots

figure;

% -------- Pie Chart --------

subplot(1, 2, 1); % Divide the figure into 1 row and 2 columns, use 1st plot

pie(pieData, pieLabels); % Create pie chart

title('Pie Chart Representation');

colormap jet; % Apply a colorful colormap

% -------- Histogram --------

subplot(1, 2, 2); % Use the 2nd plot


histogram(histData, numBins); % Create histogram

xlabel('Data Values');

ylabel('Frequency');

title('Histogram Representation');

grid on; % Show grid

OUTPUT

RESULT

MAT LAB Procedure to Plot the 2D Graphs for Pie chart and Histogram has been
Successfully implemented.
Ex. No: 05 TWO-DIMENSIONAL PLOTTING

Date: TRIGONOMETRIC FUNCTIONS

AIM

To Plot the 2D Graphs of the trigonometric functions sin(t), cos(t), sec(t), and tan(t)
over the interval [-2π, 2π] in MATLAB and analyze their behavior.

DESCRIPTION

Sine (sin t) A smooth wave oscillating between -1 and 1.

Cosine (cos t) Similar to sine but phase-shifted.

Secant (sec t) Has asymptotes where cos(t) = 0 (π/2, 3π/2, ...).

Tangent (tan t) Also has asymptotes where cos(t) = 0.

1. Two - dimensional Plots

To draw a two - dimensional plot in MATLAB, the plot command is used. The syntax is given
as follows:

plot(x, y)

where, x is a vector containing the x - coordinates of the plot and

y is a vector containing the y - coordinates of the plot.

2. Grid

To give better illustration of the coordinates on the plot, a grid is used. The
command grid is used to show the grid lines on the plot. The grid on the plot can be added or
removed by using the on and off with the grid command. When grid command without any
argument is used alternatively, it toggles the grid drawn. By default, MATLAB starts with grid
off.
3. Printing Labels

To make the plot more understandable, the two axes are labelled and a title is provided above
the top of the plot by using the following commands.

xlabel(‘string’) %Statement 1

ylabel(‘string’) %Statement 2

title(‘string’) %Statement

where, Statement 1 uses the command xlabel to print label on the x - axis. The label to be
printed is enclosed in single quotes. Similarly, Statement 2 uses the command ylabel to print
the label along y - axis. The command title in Statement 3 is used to provide a title above the
top of the graph.

PROCEDURE

1. Define t: The values of t are taken from -2π to 2π using linspace.


2. Calculate function values:

 y1 = sin(t)

 y2 = cos(t)

 y3 = sec(t) = 1/cos(t)

 y4 = tan(t) = sin(t)/cos(t)

3. Plot the functions:

 plot(t, y1, 'r', 'LineWidth', 1.5); → Red for sin(t)

 plot(t, y2, 'b', 'LineWidth', 1.5); → Blue for cos(t)

 plot(t, y3, 'g', 'LineWidth', 1.5); → Green for sec(t)

 plot(t, y4, 'm', 'LineWidth', 1.5); → Magenta for tan(t)

4. Limit y-axis: To avoid infinite values of tan(t) and sec(t), we set ylim([-5,5]).
5. Add labels, grid, and legend for clarity.
MATLAB PROGRAM

% Define time variable t from -2π to 2π

t = linspace(-2*pi, 2*pi, 1000);

% Calculate trigonometric functions

y1 = sin(t);

y2 = cos(t);

y3 = sec(t);

y4 = tan(t);

% Plot the functions

figure;

hold on; % Hold the graph to plot multiple functions on the same figure

plot(t, y1, 'r', 'LineWidth', 1.5); % Sine function in red

plot(t, y2, 'b', 'LineWidth', 1.5); % Cosine function in blue

plot(t, y3, 'g', 'LineWidth', 1.5); % Secant function in green

plot(t, y4, 'm', 'LineWidth', 1.5); % Tangent function in magenta

% Set axis limits

ylim([-5, 5]); % Limit y-axis to avoid large tan(t) and sec(t) values

% Labels and title

xlabel('t (radians)');
ylabel('Function Values');

title('2D Plot of sin(t), cos(t), sec(t), and tan(t)');

legend('sin(t)', 'cos(t)', 'sec(t)', 'tan(t)');

% Grid and axes

grid on;

ax = gca; % Get current axes

ax.XAxisLocation = 'origin'; % Set x-axis at origin

ax.YAxisLocation = 'origin'; % Set y-axis at origin

hold off;
OUTPUT

RESULT

The MAT LAB 2D Graphs for trigonometric functions sin(t), cos(t), sec(t), and tan(t)
over the interval [-2π, 2π] has been implemented succssfully.
Ex. No: 06 TWO-DIMENSENTIONAL PLOTTING

Date: SINE WAVE

AIM

To Plot a sine wave in MATLAB by defining a time variable and computing the sine
function, then visualizing it using the plot function.

DESCRIPTION

A sine wave is a periodic function that represents oscillatory motion, commonly used in
signal processing, physics, and engineering. The general mathematical equation for a sine
wave is:

y=Asin(ωt+ϕ)

Where,

 A = Amplitude (peak value of the wave)

 ω = Angular frequency (determines how fast the wave oscillates)

 t = Time (independent variable)

 φ = Phase shift (determines horizontal shift)

Syntax

Y = sin(x)

Description

y = sin(x) returns the sine of the elements of X. The sin function operates element-wise on
arrays. The function accepts both real and complex inputs. For real values of X in the interval
[-int. int], sin returns real values in the interval [-1,1]. For complex values of X, sin returns
complex values. All angles are in radians.
PROCEDURE

1. Define the time variable t

 linspace(0, 2*pi, 1000) generates 1000 points from 0 to 2π for smooth plotting.

2. Define the sine wave function y

 y = sin(t) computes the sine of each value in t.

3. Plot the sine wave using plot

 'r' → Red color


 'LineWidth', 2 → Thicker line for better visibility

4. Add labels, title, and grid

 xlabel, ylabel, and title describe the graph.


 grid on enables a background grid for clarity.
 legend('sin(t)') adds a legend.

MATLAB PROGRAM

% Define time variable t from 0 to 2π with small increments

t = linspace(0, 2*pi, 1000);

% Define sine wave function

y = sin(t);

% Plot the sine wave

figure;

plot(t, y, 'r', 'LineWidth', 2); % Red line with width 2

% Labels and Title

xlabel('Time (t)');
ylabel('Amplitude');

title('Sine Wave');

% Grid and Axis

grid on; % Enable grid

ax = gca; % Get current axes

ax.XAxisLocation = 'origin'; % Set x-axis at origin

ax.YAxisLocation = 'origin'; % Set y-axis at origin

% Display legend

legend('sin(t)');
OUTPUT

RESULT

A Sine wave in MATLAB by defining a time variable has been implemented


successfully.
Ex. No: 07 THREE-DIMENSIONAL PLOTTING

Date: SURFACE POLT FUNCTION

AIM

To Generate a 3D Surface plot in MATLAB using the function sin(√(x² + y²)) and
visualize the relationship between X, Y, and Z using the surf function.

DESCRIPTION

3D plotting in MATLAB allows visualization of functions and data in three dimensions


by representing relationships between X, Y, and Z coordinates, helping to analyze surfaces,
curves, and spatial relationships. MATLAB provides various functions for 3D plots, including
surface plots, mesh plots, contour plots, and scatter plots. These plots help in understanding
mathematical functions, engineering designs, and scientific data.

3D plotting in MATLAB is a powerful tool for visualizing and analyzing multi-


dimensional data. By using functions like surf, mesh, and plot3, users can explore
mathematical functions, data distributions, and scientific models effectively.

Surface Plot (surf)

 Used to plot 3D surfaces where the color represents the function value.

 Example: surf(X, Y, Z)
PROCEDURE

1. Define the X and Y grid:


 meshgrid(-5:0.5:5, -5:0.5:5) creates a grid of values from -5 to 5 for both x and y.
2. Define the function for Z:
 z = sin(sqrt(x.^2 + y.^2)) creates a wave-like surface.
3. Plot the 3D surface using surf(x, y, z);
 surf creates a smooth surface connecting the (x, y, z) points.
4. Enhancements:

 xlabel, ylabel, zlabel → Adds axis labels.

 title → Provides a title for the plot.

 colormap jet → Uses the "jet" color scheme.

 colorbar → Displays a color scale.

 grid on → Enables the grid.

MATLAB PROGRAM

% Define the range for X and Y


[x, y] = meshgrid(-5:0.5:5, -5:0.5:5);

% Define the function for Z


z = sin(sqrt(x.^2 + y.^2)); % Example function: sin(sqrt(x^2 + y^2))

% Create a 3D Surface Plot


figure;
surf(x, y, z);

% Labels and Title


xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('3D Surface Plot of sin(sqrt(x^2 + y^2))');

% Color and Grid


colormap jet; % Apply a colormap
colorbar; % Show color scale
grid on; % Turn on grid

OUTPUT

RESULT
The MATLAB 3D Plot using the surf function has been successfully implemented.
Ex. No: 08 THREE-DIMENSIONAL POLLTING

Date: MESH PLOT FUNCTION

AIM

To Plot a 3D mesh surface of the function 𝑐𝑜𝑠 𝑥 +𝑦 in MATLAB using the mesh
function, visualizing its oscillatory nature over a defined 2D grid.

DESCRIPTION

3D plotting in MATLAB allows visualization of functions and data in three dimensions


by representing relationships between X, Y, and Z coordinates, helping to analyze surfaces,
curves, and spatial relationships. MATLAB provides various functions for 3D plots, including
surface plots, mesh plots, contour plots, and scatter plots. These plots help in understanding
mathematical functions, engineering designs, and scientific data.

3D plotting in MATLAB is a powerful tool for visualizing and analyzing multi-


dimensional data. By using functions like surf, mesh, and plot3, users can explore
mathematical functions, data distributions, and scientific models effectively.

Mesh Plot (mesh)

 Similar to surf, but displays only wireframes without filled colors.

 Example: mesh(X, Y, Z)
PROCEDURE

1. Define the X and Y grid:


 meshgrid(-5:0.5:5, -5:0.5:5) creates a grid of values from -5 to 5 for both x and y.
2. Define the function for Z:
 z = cos(sqrt(x.^2 + y.^2)) creates a wave-like surface.
3. Plot the 3D surface using mesh(x, y, z);
 surf creates a smooth surface connecting the (x, y, z) points.
4. Enhancements:

 xlabel, ylabel, zlabel → Adds axis labels.

 title → Provides a title for the plot.

 colormap jet → Uses the " parula" color scheme.

 colorbar → Displays a color scale.

 grid on → Enables the grid.

MATLAB PROGRAM

% Define the range for X and Y


[X, Y] = meshgrid(-5:0.5:5, -5:0.5:5);

% Define the function for Z


Z = cos(sqrt(X.^2 + Y.^2)); % Example function for mesh surface

% Create a 3D Mesh Surface Plot


figure;
mesh(X, Y, Z);

% Labels and Title


xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('3D Mesh Surface Plot of cos(sqrt(X^2 + Y^2))');

% Grid and Color


colormap parula; % Apply a colormap
colorbar; % Show color scale
grid on; % Enable grid

OUTPUT

RESULT

The 3D mesh surface of the function 𝑐𝑜𝑠 𝑥 +𝑦 in MATLAB using the mesh
function has been implemented successfully.
Ex. No: 09 THREE-DIMENSIONAL PLOTTING

Date: INTERPOLATION OF SCATTERED DATA

AIM

To Generate a 3D Interpolating Scattered Surface plot in MATLAB using griddata,


scatter, surf and meshgrid function.

DESCRIPTION

3D plotting in MATLAB allows visualization of functions and data in three dimensions


by representing relationships between X, Y, and Z coordinates, helping to analyze surfaces,
curves, and spatial relationships. MATLAB provides various functions for 3D plots, including
surface plots, mesh plots, contour plots, and scatter plots. These plots help in understanding
mathematical functions, engineering designs, and scientific data.

3D plotting in MATLAB is a powerful tool for visualizing and analyzing multi-


dimensional data. By using functions like surf, mesh, and plot3, users can explore
mathematical functions, data distributions, and scientific models effectively.

Computes a function value z for given x, y based on the


peaks(x,y)
MATLAB peaks function.

Creates a regular grid of Xq, Yq in the range -2 to 2 with


meshgrid(-2:0.1:2, -2:0.1:2)
0.1 spacing.

Interpolates scattered data (x, y, z) onto a grid using cubic


griddata(x,y,z,Xq,Yq,'cubic')
interpolation.

scatter3(x, y, z, 'filled') Plots scattered 3D data points with filled markers.

surf(Xq, Yq, Zq) Creates a smooth surface plot of the interpolated data.
MATLAB PROGRAM

x = rand(100,1)*4 - 2;

y = rand(100,1)*4 - 2;

z = peaks(x,y);

% Define a regular grid for interpolation

[Xq,Yq] = meshgrid(-2:0.1:2, -2:0.1:2);

% Interpolate scattered data to the regular grid using griddata

Zq = griddata(x,y,z,Xq,Yq,'cubic');

% Plot the scattered data and the interpolated surface

figure;

scatter3(x, y, z, 'filled'); % Plot scattered data points

hold on;

surf(Xq, Yq, Zq); % Plot interpolated surface

hold off;

xlabel('X');

ylabel('Y');

zlabel('Z');

title('Interpolating Scattered Data');

legend('Scattered Data', 'Interpolated Surface');


OUTPUT

RESULT

The 3D Interpolating Scattered Surface plot in MATLAB using griddata, scatter, surf
and meshgrid function has been implemented successfully.
Ex. No: 10
SIMPLE CALCULATOR USING GUI
Date:

AIM

To Implement the simple calculator using GUI Components in MAT LAB.

DESCRIPTION

A Graphical User Interface (GUI) in MATLAB allows users to interact with a program
using graphical components instead of command-line inputs. MATLAB provides App
Designer and GUIDE (deprecated) for creating GUIs.

uifigure Creates a GUI window (figure) to hold UI components.

uieditfield Creates an input or display box for text or numeric values.

uibutton Creates push buttons for user interaction.

uilabel Displays static text labels in the GUI.

uislider Creates a slider for selecting numeric values.

uicheckbox Adds a checkbox for binary choices (checked/unchecked).

uipanel Groups multiple components together in a panel.

uitabgroup / uitab Creates tabbed panels for organizing GUI content.

listbox Displays a list of selectable options.

axes Used to plot graphs inside the GUI.


MATLAB PROGRAM

function simpleCalculator

% Create the main figure

fig = uifigure('Name', 'Simple Calculator', 'Position', [500, 300, 300, 400]);

% Create an edit field to display input and result

displayBox = uieditfield(fig, 'text', 'Position', [20, 320, 260, 40], 'Editable', 'off', 'FontSize',
16);

% Define button labels

buttonLabels = {'7', '8', '9', '/', ...

'4', '5', '6', '*', ...

'1', '2', '3', '-', ...

'0', 'C', '=', '+'};

% Define positions for buttons

xPos = [20, 90, 160, 230]; % X-coordinates

yPos = [270, 220, 170, 120]; % Y-coordinates

% Store the expression being entered

expression = "";

% Create buttons

for i = 1:4
for j = 1:4

btnIndex = (i-1) * 4 + j;

btn = uibutton(fig, 'push', 'Text', buttonLabels{btnIndex}, ...

'Position', [xPos(j), yPos(i), 60, 50], 'FontSize', 14, ...

'ButtonPushedFcn', @(btn, event) buttonCallback(btn.Text));

end

end

% Callback function for button actions

function buttonCallback(btnText)

switch btnText

case 'C' % Clear button

expression = "";

displayBox.Value = "";

case '=' % Evaluate the expression

try

result = eval(expression); % Compute result

displayBox.Value = num2str(result);

expression = num2str(result); % Store result for next operation

catch

displayBox.Value = 'Error';

expression = "";

end

otherwise % Append numbers and operators


expression = expression + btnText;

displayBox.Value = expression;

end

end

end

OUTPUT

RESULT

The Simple calculator using GUI Components in MAT LAB has been implemented
successfully.

You might also like