Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab 03 MATLAB

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Haider Yaseen MEEN201101082

Lab 03
Objective:
Introduction to MATLAB: generating graphical plotings, using curve fitting and dealing
with GUIs with certain applications. (Part-III)

Theory:
Graphical Ploting:
MATLAB is a powerful tool for generating graphical plots and visualizations. It provides a wide
range of built-in functions for creating different types of plots, such as line plots, scatter plots, bar
plots, histogram plots, and many others.
The basic syntax for creating a plot in MATLAB involves defining the data to be plotted and using
the appropriate plot function to generate the plot. For example, to create a line plot, the plot
function is used, while a scatter plot can be generated using the scatter function.
In addition to the basic plot functions, MATLAB provides a wide range of customization options
for fine-tuning the appearance and behavior of plots. This includes options for controlling line
styles, marker styles, axis limits, grid lines, legends, and many others. These options can be set
using various functions, such as set, xlabel, ylabel, title, legend, and many others.
MATLAB also provides a range of tools for analyzing and manipulating data prior to plotting.
This includes functions for filtering, smoothing, and resampling data, as well as tools for
computing statistics and performing various mathematical operations.
Overall, MATLAB provides a powerful and flexible platform for generating graphical plots and
visualizations, making it an essential tool for data analysis, scientific research, and engineering
applications.

1|Page
Haider Yaseen MEEN201101082

Figure 1 Graphical plotting

Curve Fitting:
Curve fitting in MATLAB is the process of finding a mathematical function that best fits a given
set of data points. It involves finding the best set of parameters that minimize the difference
between the model function and the observed data. Curve fitting is an important tool in data
analysis and is widely used in many fields, including engineering, physics, and economics.
MATLAB provides several built-in functions for curve fitting, including polyfit, lsqcurvefit, and
cftool. The polyfit function fits a polynomial curve to the data, while the lsqcurvefit function fits
an arbitrary function to the data using a least-squares optimization algorithm. The cftool function
provides a graphical interface for interactive curve fitting.
In addition to the built-in functions, MATLAB provides a wide range of tools for analyzing and
manipulating data prior to curve fitting. This includes functions for filtering, smoothing, and
resampling data, as well as tools for computing statistics and performing various mathematical
operations.

2|Page
Haider Yaseen MEEN201101082

Figure 2 Curve fitting

Graphical User Interface (GUIs):


Graphical User Interfaces (GUIs) are a powerful tool in MATLAB for creating interactive
applications with user-friendly interfaces. A GUI is essentially a collection of graphical objects
such as buttons, sliders, text boxes, and menus, which can be arranged and manipulated to create
an interactive interface. The user can interact with the GUI by clicking buttons, dragging sliders,
or entering text into text boxes.
MATLAB provides a comprehensive set of tools for creating GUIs, including the GUIDE
(Graphical User Interface Development Environment) tool, which provides a drag-and-drop
interface for creating GUIs, and the App Designer tool, which provides a more modern and flexible
interface for creating GUIs.
GUIs can be used for a wide range of applications, such as data visualization, control systems, and
image processing. For example, a GUI can be used to display a real-time plot of data, with options
for adjusting the plot range and other parameters. Another example is a GUI for controlling a robot
arm, where the user can adjust the arm position and orientation using sliders and buttons.
To create a GUI in MATLAB, the basic steps are:

1. Design the layout of the GUI using the GUI design tool.

3|Page
Haider Yaseen MEEN201101082

2. Add and customize the various graphical components such as buttons, sliders, and text
boxes.
3. Write callback functions to handle user interactions with the GUI.
4. Test the GUI and make any necessary modifications.
MATLAB provides a wide range of functions for customizing and controlling the behavior of GUI
components, such as set, get, uicontrol, and many others.

Figure 3 GUIs Calculator

Task no 1:
Plot a set of data points using two or more variables from your lab experimentation o r
any semester project/ complex engineering problem/ assignment.
Code:
clc; % clear command window

4|Page
Haider Yaseen MEEN201101082

clear all; % clear all previously defined varirables

t= linspace(0,10,50);

f= log(t);

g=sin(t);

plot(t,f, t,g)

Figure 4 Task 01 Result

Task no 02:

5|Page
Haider Yaseen MEEN201101082

Plot a function as a curve using two or more variables from your lab experimentation or
any semester project/ complex engineering problem/ assignment. Add proper labels,
symbols and colours to the graph as well.
Code:
clc; % clear command window
clear all; % clear all previously defined varirables
t=[0:3];
y1=t;
y2=t.^.5;
y3=t.^2;
plot(t,y1,t,y2,t,y3)
xlabel=('time,s')
ylabel=('y(t)')
legend('y1','y2','y3')
title('y123 over time')

Figure 5 Task 02 Result

6|Page
Haider Yaseen MEEN201101082

Task no 03:

• Plot a set of curves in a single window using four or five variables from your lab
experimentation or any semester project/ complex engineering problem/ assignment.

Code:
clc; % clear command window
clear all; % clear all previously defined varirables
% Generate data
x = linspace(0, 2*pi, 100);
y1 = sin(x);
y2 = cos(x);
y3 = exp(-x);
y4 = x.^2;

% Plot curves
figure;
hold on;
plot(x, y1);
plot(x, y2);
plot(x, y3);
plot(x, y4);

% Set plot properties


title('Multiple Curves');
xlabel('x');
ylabel('y');
legend('y1 = sin(x)', 'y2 = cos(x)', 'y3 = exp(-x)', 'y4 = x^2');
grid on;

7|Page
Haider Yaseen MEEN201101082

Figure 6 Task 03 First part Result

• Plot a set of curves (/ functions) in a multi window screen using subplot command
four or five variables from your lab experimentation or any semester project/
complex engineering problem/ assignment

Code:
clc; % clear command window
clear all; % clear all previously defined varirables
% Generate data
x = linspace(0, 2*pi, 100);
y1 = sin(x);
y2 = cos(x);
y3 = exp(-x);

8|Page
Haider Yaseen MEEN201101082

y4 = x.^2;

% Create a figure with subplots


figure;

% Subplot 1
subplot(2, 2, 1);
plot(x, y1);
title('y1 = sin(x)');
xlabel('x');
ylabel('y');

% Subplot 2
subplot(2, 2, 2);
plot(x, y2);
title('y2 = cos(x)');
xlabel('x');
ylabel('y');

% Subplot 3
subplot(2, 2, 3);
plot(x, y3);
title('y3 = exp(-x)');
xlabel('x');
ylabel('y');

% Subplot 4
subplot(2, 2, 4);

9|Page
Haider Yaseen MEEN201101082

plot(x, y4);
title('y4 = x^2');
xlabel('x');
ylabel('y');

% Adjust spacing
sgtitle('Multiple Curves');

Figure 7 Task no 03 second part Result

10 | P a g e
Haider Yaseen MEEN201101082

Task no 04:

Find the best polynomial to fit a given data set. (Curve_Fitting.m)

Code:

clc; % clear command window

clear all; % clear all previously defined varirables

% Given data points

x = [1, 2, 3, 4, 5];

y = [0.5, 2.5, 2, 4, 3.5];

% Polynomial degree

degree = 3;

% Fit a polynomial to the data

coefficients = polyfit(x, y, degree);

% Generate curve based on fitted polynomial

xFit = linspace(min(x), max(x), 100);

yFit = polyval(coefficients, xFit);

% Plot the data points and the fitted curve

figure;

plot(x, y, 'bo', 'MarkerSize', 8, 'LineWidth', 1.5);

hold on;

11 | P a g e
Haider Yaseen MEEN201101082

plot(xFit, yFit, 'r-', 'LineWidth', 2);

hold off;

grid on;

% Set plot properties

title('Polynomial Curve Fitting');

xlabel('x');

ylabel('y');

legend('Data Points', 'Fitted Curve');

Figure 8 Task 04 Result

12 | P a g e
Haider Yaseen MEEN201101082

Task no 5:
Create a graph of a surface in 3-space using the following data:

• x = (0:2*pi/20:2*pi)'
• y = (0:4*pi/40:4*pi)'
• z = cos(X).*cos(2*Y)

Also, plot the mesh of given data along with the contour plot.
Code:
clc; % clear command window
clear all; % clear all previously defined varirables
x = (0:2*pi/20:2*pi);

y = (0:4*pi/40:4*pi);

[X,Y] = meshgrid(x,y);

Z = cos(X).*cos(2*Y);

contour(X,Y,Z)

Figure 9 Task 05 Result

13 | P a g e
Haider Yaseen MEEN201101082

Task no 06:
Design a GUI of a Basic Calculator with all the arithmetic operations, display of inputs
and output.

Figure 10 Task 06 Result (GUIs Calculator)

Code:
function varargout = matlab_tutorial_calculator(varargin)
% MATLAB_TUTORIAL_CALCULATOR MATLAB code for matlab_tutorial_calculator.fig
% MATLAB_TUTORIAL_CALCULATOR, by itself, creates a new
MATLAB_TUTORIAL_CALCULATOR or raises the existing
% singleton*.
%

14 | P a g e
Haider Yaseen MEEN201101082

% H = MATLAB_TUTORIAL_CALCULATOR returns the handle to a new


MATLAB_TUTORIAL_CALCULATOR or the handle to
% the existing singleton*.
%
% MATLAB_TUTORIAL_CALCULATOR('CALLBACK',hObject,eventData,handles,...)
calls the local
% function named CALLBACK in MATLAB_TUTORIAL_CALCULATOR.M with the given
input arguments.
%
% MATLAB_TUTORIAL_CALCULATOR('Property','Value',...) creates a new
MATLAB_TUTORIAL_CALCULATOR or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before matlab_tutorial_calculator_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to matlab_tutorial_calculator_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help matlab_tutorial_calculator

% Last Modified by GUIDE v2.5 13-May-2023 21:12:41

% Begin initialization code - DO NOT EDIT


gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @matlab_tutorial_calculator_OpeningFcn, ...

15 | P a g e
Haider Yaseen MEEN201101082

'gui_OutputFcn', @matlab_tutorial_calculator_OutputFcn, ...


'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before matlab_tutorial_calculator is made visible.


function matlab_tutorial_calculator_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to matlab_tutorial_calculator (see VARARGIN)

% Choose default command line output for matlab_tutorial_calculator


handles.output = hObject;

% Update handles structure


guidata(hObject, handles);

16 | P a g e
Haider Yaseen MEEN201101082

% UIWAIT makes matlab_tutorial_calculator wait for user response (see UIRESUME)


% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = matlab_tutorial_calculator_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure


varargout{1} = handles.output;

function screen_Callback(hObject, eventdata, handles)


% hObject handle to screen (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of screen as text


% str2double(get(hObject,'String')) returns contents of screen as a double

% --- Executes during object creation, after setting all properties.


function screen_CreateFcn(hObject, eventdata, handles)

17 | P a g e
Haider Yaseen MEEN201101082

% hObject handle to screen (see GCBO)


% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.


% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in number7.


function number7_Callback(hObject, eventdata, handles)
% hObject handle to number7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'7'));

% --- Executes on button press in number8.


function number8_Callback(hObject, eventdata, handles)
% hObject handle to number8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'8'));

% --- Executes on button press in number9.

18 | P a g e
Haider Yaseen MEEN201101082

function number9_Callback(hObject, eventdata, handles)


% hObject handle to number9 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'9'));

% --- Executes on button press in number4.


function number4_Callback(hObject, eventdata, handles)
% hObject handle to number4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'4'));

% --- Executes on button press in number5.


function number5_Callback(hObject, eventdata, handles)
% hObject handle to number5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'5'));

% --- Executes on button press in number6.


function number6_Callback(hObject, eventdata, handles)
% hObject handle to number6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

19 | P a g e
Haider Yaseen MEEN201101082

S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'6'));

% --- Executes on button press in number1.


function number1_Callback(hObject, eventdata, handles)
% hObject handle to number1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'1'));

% --- Executes on button press in number2.


function number2_Callback(hObject, eventdata, handles)
% hObject handle to number2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'2'));

% --- Executes on button press in number3.


function number3_Callback(hObject, eventdata, handles)
% hObject handle to number3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'3'));

% --- Executes on button press in coma.

20 | P a g e
Haider Yaseen MEEN201101082

function coma_Callback(hObject, eventdata, handles)


% hObject handle to coma (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if not(strcmp(get(handles.screen,'string'),''))
S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'.'));
end

% --- Executes on button press in number0.


function number0_Callback(hObject, eventdata, handles)
% hObject handle to number0 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S= get(handles.screen,'string');
set(handles.screen,'string',strcat(S,'0'));

% --- Executes on button press in pi.


function pi_Callback(hObject, eventdata, handles)
% hObject handle to pi (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if strcmp(get(handles.screen,'string'),'')
set(handles.screen,'string','3.14');
end

% --- Executes on button press in reset.

21 | P a g e
Haider Yaseen MEEN201101082

function reset_Callback(hObject, eventdata, handles)


% hObject handle to reset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set (handles.screen,'string', '');

% --- Executes on button press in divide.


function divide_Callback(hObject, eventdata, handles)
% hObject handle to divide (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global A Selector
A = str2num(get(handles.screen,'string'));
Selector= 1;
set(handles.screen,'string','');

% --- Executes on button press in mulitiply.


function mulitiply_Callback(hObject, eventdata, handles)
% hObject handle to mulitiply (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global B Selector
B = str2num(get(handles.screen,'string'));
Selector= 2;
set(handles.screen,'string','');

% --- Executes on button press in minus.


function minus_Callback(hObject, eventdata, handles)

22 | P a g e
Haider Yaseen MEEN201101082

% hObject handle to minus (see GCBO)


% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global C Selector
if strcmp(get(handles.screen,'string'),'')
set(handles.screen,'string','-');
else
C = str2num(get(handles.screen,'string'));
Selector= 3;
set(handle.screen,'string','');
end

% --- Executes on button press in root.


function root_Callback(hObject, eventdata, handles)
% hObject handle to root (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.screen,'string',num2str(sqrt(abs(str2num(get(handles.screen,'string'))))));

% --- Executes on button press in square.


function square_Callback(hObject, eventdata, handles)
% hObject handle to square (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.screen,'string',num2str(str2num(get(handles.screen,'string'))^2));

% --- Executes on button press in equals.


function equals_Callback(hObject, eventdata, handles)

23 | P a g e
Haider Yaseen MEEN201101082

% hObject handle to equals (see GCBO)


% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global A B C D Selector
switch Selector
case 1
A = A/str2num(get(handles.screen,'string'));
set(handles.screen,'string',num2str(A));
case 2
B = B*str2num(get(handles.screen,'string'));
set(handles.screen,'string',num2str(B));
case 3
C = C-str2num(get(handles.screen,'string'));
set(handles.screen,'string',num2str(C));
case 4
D = D+str2num(get(handles.screen,'string'));
set(handles.screen,'string',num2str(D));
end
% --- Executes on button press in plus.
function plus_Callback(hObject, eventdata, handles)
% hObject handle to plus (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global D Selector
D = str2num(get(handles.screen,'string'));
Selector= 4;
set(handles.screen,'string','');

24 | P a g e
Haider Yaseen MEEN201101082

25 | P a g e

You might also like