ENGINEERING MATLAB APPLICATIONS
M-Files Functions Examples
11/21/2024 1
OUTLINE
• M-Files
• Functions
• Create functions
• Call the functions
• Examples
11/21/2024 2
M-Files
• M-Files
Recommended for the Script files
clc; % Clears the Command Window
clear all; % Clear all the variables in the Workspace
close all; % Close all of the opened Figure Windows
format long g % (format short g) Set output format
% Scaled fixed point format with 15 digits for double
and 7 digits for single.
11/21/2024 3
Functions
In Matlab function command is used to create the user-defined functions.
There are two options;
You can create the functions in seperate files only if you save the file with the
same name of the function.
You may create the functions in the script files at the end of your codes and
call them in the same *.m-file.
function [out1, out2, ...] = fonksiyonAdı (in1, in2, ...)
operation
end
11/21/2024 4
Examples
• Ex 1:
Write an algorithm which ask for b and h values as ‘input’ to
h calculate the area, perimeter, center of gravity and moment of
inertia to write in the command window.
b Command Window
MATLAB
function [A, I, C, xg, yg]=Dikdortgen(b,h) [A, I, C, xg, yg]=Dikdortgen(30,60)
A=b*h; -----------Section Properties--------------
I=1/12*b*h^3; Alan=1800
C=2*(b+h); I=540000
xg=b/2; C=180
yg=h/2; Centroid=(15 30)
disp('-----------Section Properties--------------') A = 1800
disp(['Alan=',num2str(A)]) I = 540000
disp(['I=',num2str(I)]) C = 180
disp(['C=',num2str(C)]) xg = 15
disp(['Centroid=(',num2str([xg yg]),')']) yg = 30
end
11/21/2024 5
Examples
• Ex 2:
Using the Dikdortgen.m function for a beam with L= 5 m span and w= 10
N/m uniformly distributed load acting on it, calculate the stresses at top
and bottom fibers. b=30 cm, h=60 cm.
𝑤∙𝐿2 𝑀𝑚𝑖𝑑 ∙𝑐
𝑀𝑚𝑖𝑑 = 8
; −𝜎𝑡𝑜𝑝 = 𝜎𝑏𝑜𝑡 = 𝐼
clc
clear all Sub program
close all
[A, I, C, xg, yg]=Dikdortgen(0.3,0.6)
w=10; % N/m
L=5; % m
Mmid=w*L^2/8;
Sigma_top=-Mmid*yg/I;
Sigma_bot=Mmid*yg/I;
disp(['Sigma_top=',num2str(Sigma_top),' N/m^2'])
disp(['Sigma_top= ',num2str(Sigma_bot),' N/m^2']) Sigma_top=-1736.1111 N/m^2
Sigma_top= 1736.1111 N/m^2
11/21/2024 6