4 Scripts and Functions - Big
4 Scripts and Functions - Big
>> y = sqrt(x)
y =
2.2361 2.6458 3.8730
Copyright © Dr. Mohammed Hawa Electrical Engineering Department, University of Jordan 7
Function Composition
• Composition: Using a function as an
argument of another function
• Allowed in MATLAB.
• Just check the number and placement of
parentheses when typing such
expressions.
• sin(sqrt(x)+1)
• log(x.^2 + sin(5))
Copyright © Dr. Mohammed Hawa Electrical Engineering Department, University of Jordan 8
Which expression is correct?
• You want to find sinଶ . What do you write?
• (sin(x))^2
• sin^2(x)
• sin^2x
• sin(x^2)
• sin(x)^2
• Solution: Only first and last expressions are
correct.
% L. Shure, 4-20-92.
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision: 5.9.4.2 $ $Date: 2004/07/05 17:02:08 $
x = r.*cos(th);
y = r.*sin(th);
u = 3*x;
z = u + 6*y.^2;
>> x
x =
3
>> y
??? Undefined function or variable 'y'.
>> u
??? Undefined function or variable 'u'.
>> z
??? Undefined function or variable 'z'.
>> q
q =
303
Copyright © Dr. Mohammed Hawa Electrical Engineering Department, University of Jordan 21
Exercise
function show_date
clear
clc
date
>> t = 0:0.1:5;
>> [distance_dropped, velocity] = drop(10, t);
>> plot(t, velocity)
function y = subfun_demo(a)
y = a - mean(a);
function w = mean(x)
w = sqrt(sum(x.^2))/length(x);
>>a = [4 -4];
>>b = a - mean(a)
b =
4 -4
function y = f1(x)
y = x + 2*exp(-x) - 3;
1.5
• There is a zero
1
near 0.5
0.5
and one
0
near 3.
-0.5
-1
-1.5
-1 0 1 2 3 4 5
>> fzero(@f1, 3)
ans =
• where @function 2.8887
• function y = f2(x)
• y = 1-x.*exp(-x);
• x = fminbnd(@f2, 0, 5) returns x = 1
• How would I find the min value of f2? (i.e. 0.6321)
function f = f4(x)
f = x(1).*exp(-x(1).^2-x(2).^2);
>>fminsearch(@f4,[0,0])
ans =
-0.7071 0.000
>> sqrtsum(3, 4)
ans =
5
>> A = 6; B = 4;
>> z = plane(2,8)
z =
44
>> a = dlmread('ascii.txt')
a =
1 2 3 4
5 6 7 8
9 10 11 12
>> a = xlsread('data.xls')
a =
10 30 50 60
15 20 25 30
30 31 32 33
80 82 84 86
>> c = imread('cat.jpg');
>> imshow(c);
>>
>> imshow(255-c); % inverse
plot(t, y);
xlabel('Time (s)');
ylabel('Amplitude');
f = Fs*(-N/2:N/2-1)/N;
y_fft = fftshift(abs(fft(y)));
figure;
plot(f, y_fft);
xlabel('Frequency (Hz)');
ylabel('Amplitude');
1 150
0.8
0.6
0.4
100
0.2
Amplitude
Amplitude
0
-0.2
50
-0.4
-0.6
-0.8
-1 0
0 0.2 0.4 0.6 0.8 1 1.2 1.4 -6000 -4000 -2000 0 2000 4000 6000
Time (s) Frequency (Hz)
0.8 2000
0.6 1800
1600
0.4
1400
0.2
1200
Amplitude
Amplitude
0
1000
-0.2
800
-0.4
600
-0.6
400
-0.8 200
-1 0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5
Time (s) Frequency (Hz) 4
x 10
0.3 4500
4000
0.2
3500
0.1
3000
0
Amplitude
Amplitude
2500
-0.1 2000
1500
-0.2
1000
-0.3
500
-0.4 0
0 1 2 3 4 5 6 7 8 9 -1.5 -1 -0.5 0 0.5 1 1.5
Time (s) Frequency (Hz) 4
x 10
0.8 1800
0.6 1600
0.4 1400
0.2 1200
Amplitude
Amplitude
0 1000
-0.2 800
-0.4 600
-0.6 400
-0.8 200
-1 0
0 0.5 1 1.5 2 2.5 -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5
Time (s) Frequency (Hz) 4
x 10