Probability, Statistics and Interpolation
Cheng-Liang Chen
PSE
LABORATORY
Department of Chemical Engineering National TAIWAN University
Chen CL
1
Statistics, Histograms, and Probability A Histogram is a plot of the frequency of occurrence of data values versus the values themselves
Test 1 61 61 61 65 67 69 72 72 74 74 76 77 83 83 85 88 89 92 92 93 93 95 98
Test 2 66 66 69 72 72 74 75 76 77 78 78 79 79 80 80 81 83 84 85 87 88 90 9 0 94
Test 1
∼ 69 69 range, range, five in 70 ∼ 79 79,, five in 80 ∼ 89 89,, five in 90 ∼ 99 99;; Test 2 ⇒ tw twoo scores scores in 60 ∼ 69 69 range, range, nine in 70 ∼ 79 79,, 89,, seven in 80 ∼ 89 twoo in 90 ∼ 99 tw ⇒
five sco scores res in 60
Chen CL
1
Statistics, Histograms, and Probability A Histogram is a plot of the frequency of occurrence of data values versus the values themselves
Test 1 61 61 61 65 67 69 72 72 74 74 76 77 83 83 85 88 89 92 92 93 93 95 98
Test 2 66 66 69 72 72 74 75 76 77 78 78 79 79 80 80 81 83 84 85 87 88 90 9 0 94
Test 1
∼ 69 69 range, range, five in 70 ∼ 79 79,, five in 80 ∼ 89 89,, five in 90 ∼ 99 99;; Test 2 ⇒ tw twoo scores scores in 60 ∼ 69 69 range, range, nine in 70 ∼ 79 79,, 89,, seven in 80 ∼ 89 twoo in 90 ∼ 99 tw ⇒
five sco scores res in 60
Chen CL
% Coll lle ect the sc sco ores in ea eac ch bin. test1 = [5, 5, 5, 5]; test2 = [2, 7, 9, 2]; % Sp Spec ecif ify y th the e bi bin n ce cent nter ers. s. x = [6 [64. 4.5, 5, 74 74.5 .5, , 84 84.5 .5, , 94 94.5 .5]; ]; subplot(2,1,1) bar(x, test1), axis([60 100 0 10]),... title tit le(’ (’Hi Histo stogr gram am of sco score res s fo for r te test st 1’ 1’),. ),... .. xlabel(’Score xlabel( ’Score range’ range’),... ),... ylabel( ylab el(’Nu ’Number mber of scor scores’ es’) ) % subplot(2,1,2) bar(x, test2), axis([60 100 0 10]),... title tit le(’ (’Hi Histo stogr gram am of sco score res s fo for r te test st 2’ 2’),. ),... .. xlabel(’Score xlabel( ’Score range’ range’),... ),... ylabel( ylab el(’Nu ’Number mber of scor scores’ es’) )
2
Chen CL
3 Histogram of scores for test 1 10
s e r o c s f o r e b m u N
8 6 4 2 0 60
65
70
75
80 Score range
85
90
95
100
90
95
100
Histogram of scores for test 2 10
s e r o c s f o r e b m u N
8 6 4 2 0 60
65
70
75
80 Score range
85
Chen CL
4
Ex: Breaking Strength of Thread To ensure proper quality control, a thread manufacturer selects samples and tests them for breaking strength. Suppose that 20 thread samples are pulled until they break, and the breaking force is measured in newtons rounded off to integer values. The breaking force values recorded were 92, 94, 93, 96, 93, 94, 95, 96, 91, 93, 95, 95, 95, 92, 93, 94, 91, 94, 92, and 93. Plot the histogram of the data.
Solution: Six outcomes (91, 92, 93, 94, 95, 96)
⇒ six bins
% Thread breaking strength data for 20 tests. y = [92, 94, 93, 96, 93, 94, 95, 96, 91, 93,... 95, 95, 95, 92, 93, 94, 91, 94, 92, 93]; % The six possible outcomes are: 91, 92, 93, 94, 95, 96 x = [91:96]; hist(y, x), axis([90 97 0 6]),... xlabel(’Thread strength (newtons)’),... ylabel(’Absolute frequency’),... title(’Absolute frequency histogram for 20 tests’)
Chen CL
5 Absolute frequency histogram for 20 tests 6
5
4 y c n e u q e r f
e t u l o s b A
3
2
1
0
91
92
93 94 Thread strength (newtons)
95
96
Chen CL
6
Note:
100 samples, 6 outcomes (91, 92, 93, 94, 95, 96) with number of times: 13, 15, 22, 19, 17, 14
% Thread breaking strength data for 100 tests. y = [91*ones(1,13), 92*ones(1,15), 93*ones(1,22),... 94*ones(1,19), 95*ones(1,17), 96*ones(1,14)]; % The six possible outcomes are: 91, 92, 93, 94, 95, 96 x = [91:96]; hist(y, x),... xlabel(’Thread strength (newtons)’),... ylabel(’Absolute frequency’),... title(’Absolute frequency histogram for 100 tests’)
Chen CL
7 Absolute frequency histogram for 100 tests 25
20
y c 15 n e u q e r f e t u l o s b 10 A
5
0
91
92
93 94 Thread strength (newtons)
95
96
Chen CL
Relative Frequency: 100 samples, 6 outcomes (91, 92, 93, 94, 95, 96) with number of times: 13, 15, 22, 19, 17, 14 tests = 100; y = [13, 15, 22, 19, 17, 14]/tests; x = [91:96]; bar(x, y),... xlabel(’Thread strength (newtons)’),... ylabel(’Relative frequency’),... title(’Absolute frequency histogram for 100 tests’)
OR tests = 100; y = [91*ones(1,13), 92*ones(1,15), 93*ones(1,22),... 94*ones(1,19), 95*ones(1,17), 96*ones(1,14)]; x = [91:96]; [z, x] = hist(y, x); bar(x, z/tests),... xlabel(’Thread strength (newtons)’),... ylabel(’Relative frequency’),... title(’Absolute frequency histogram for 100 tests’)
8
Chen CL
9 Absolute frequency histogram for 100 tests 0.25
0.2
y c 0.15 n e u q e r f e v i t a l e R 0.1
0.05
0
91
92
93 94 Thread strength (newtons)
95
96
Chen CL
10
Test Your Understanding T7.1-1 In 50 tests of thread, the number of times 91, 92, 93, 94, 95, or 96 newtons was measured was 7, 8, 10, 6, 12, and 7, respectively. Obtain the absolute and relative frequency histograms.
Chen CL
11
Histogram Functions Command
Description
bar(x,y)
Creates a bar chart of y versus x
hist(y)
Aggregates the data in the vector coloryellowy into 10 bins evenly spaced between the minimum and maximum values in y Aggregates the data in the vector y into n bins evenly spaced between the minimum and maximum values in y
hist(y,n) hist(y,x)
Aggregates the data in the vector y into bins whose center locations are specified by vector x. The bin widths are the distances between the centers
[z,x]=hist(y)
Same as hist(y) but returns two vectors z and x that contain the frequency count and the bin locations Same as hist(y,n) but returns two vectors z and x that contain the frequency count and the bin locations
[z,x]=hist(y,n) [z,x]=hist(y,x)
Same as hist(y,x) but returns two vectors z and x that contain the frequency count and the bin locations (return the same x)
Chen CL
12
Probability Comparison of theory and experiment for 100 rolls of a single die
Theory: 16 = 16.67% for 1, 2, 3, 4, 5, 6 Experi. 21, 14, 18, 16, 19, 12 occurrences for 1, 2, 3, 4, 5, 6
Chen CL
13
Probability Comparison of theory and experiment for 100 rolls of two dice Probabilities for the sum of two dice Sum Probability ( 36)
×
Sum Frequency
2 1
3 2
4 3
5 4
6 5
7 6
8 5
9 4
10 3
11 2
12 1
10 7
11 10
12 4
Data for two dice 2 5
3 5
4 8
5 11
6 20
7 10
8 8
9 12
Chen CL
14
Test Your Understanding T7.1-2 If you roll a pair of balanced dice 200 times, how many times would you expect to obtain a sum of 7 ? How many times would you expect to obtain a sum of either 9, 10 or 11 ? How many times would you expect to obtain a sum less than 7 ? (ANS: 33, 50, 106)
Chen CL
15
Data: Heights of 100 Men 20 Years of Age The heights were recorded to the nearest 1/2 inch. Plot the scaled frequency histogram . Height (inches)
Frequency
Height (inches)
Frequency
64.0 64.5 65.0
1 0 0
70.0 70.5 71.0
9 8 7
65.5 66.0 66.5
0 2 4
71.5 72.0 72.5
5 4 4
67.0 67.5 68.0 68.5
5 4 8 11
73.0 73.5 74.0 74.5
3 1 1 0
69.0 69.5
12 10
75.0
1
Chen CL
16
Scaled Frequency Histogram % Absolute frequency data y_abs = [1,0,0,0,2,4,5,4,8,11,12,10,9,8,7,5,4,4,3,1,1,0,1] binwidth = .5; % Compute scaled frequency data area = binwidth*sum(y_abs); y_scaled = y_abs/area; % Define the bins bins = [64:binwidth:75]; % Plot the scaled histogram bar(bins, y_scaled),... xlabel(’Height (inches)’), ylabel(’Scaled frequency’) % Compute prob. of a height lying between 67, 69 inches % 6th to 11th values, (.1+.08+.16+.22+.24)*(.5)=.4, 40% prob = cumsum(y_scaled)*binwidth; prob67_69 = prob(11)-prob(6)
Chen CL
17 0.25
0.2
y 0.15 c n e u q e r f d e l a c S
0.1
0.05
0 62
64
prob67_69 = 0.4000
66
68 70 Height (inches)
72
74
76
Chen CL
18
Continuous Approximation to the Scaled Histogram Normal Probability Function
p(x) =
1 √ e−(x−µ) /2σ σ 2π 2
2
Chen CL
Effect of σ Values on Normal Distribution Curve ( µ = 10)
19
Chen CL
Probability Interpretation of (a) the µ
Pr(x µ σ < x < µ + σ) = 68.3% Pr(x µ 2σ < x < µ + 2σ) = 95.5% Pr(x µ 3σ < x < µ + 3σ) = 99.7%
| − | − | −
20
± σ and (b) the µ ± 2σ
Chen CL
21
Estimating the Mean and Standard Deviation
1 x = (x1 + n σ =
n
···
n i=1(xi
n
1 + xn) = xi n i=1
− x)2
−1
Statistical Functions Command
Description
mean(x) median(x) std(x) cumsum(x)
Calculate the mean of the data stored in vector x Calculate the median of the data stored in vector x Calculate the standard deviation of the data stored in vector x Creates a vector the same size as x, containing the cumulative sum of the elements of x
Chen CL
22
Ex: Mean and Standard Deviation of Heights Statistical analysis of data on human proportions is required in many engineering applications. For example, designers of submarine crew quarters need to know how small they can make bunk lengths without eliminating a large percentage of prospective crew members. Use MATLAB to estimate the mean and standard deviation for the preceding height data.
% Absolute frequency data y_abs = [1,0,0,0,2,4,5,4,8,11,12,10,9,8,7,5,4,4,3,1,1,0,1] binwidth = .5; % Define the bins bins = [64:binwidth:75]; % Reconstruct the original (raw) height data % from the absolute frequency data % Fill the vector y_raw with the raw data % Start with a null vector
Chen CL
23
y_raw = []; for i = 1:length(y_abs) if y_abs(i) > 0 new = bins(i)*ones(1, y_abs(i)); else new = [ ]; end y_raw = [y_raw, new]; end % Compute the mean (69.3) and standard deviation (1.96) mu = mean(y_raw), sigma = std(y_raw)
Chen CL
24
Use Error Function to to Compute (Normal) Probability
Pr(x
Pr(a
≤
≤x≤
−√ −√ − −√
1 b µ b) = 1 + erf + erf 2 σ 2 1 b µ b) = erf 2 σ 2
a µ erf σ 2
Chen CL
25
Ex: Mean and Standard Deviation of Heights Use the results of last example to estimate how many twenty-year old men are no taller than 68 68 inches. inches. How many are within 3 inches of the mean ?
Pr(x (69..3 Pr(69
≤ 68)
=
− 3 ≤ x ≤ 69 69..3 + 3)
=
− √ √ − −√
1 68 69 69..3 1 + erf + erf 2 1.96 2 1 3 3 erf erf 2 1.96 2 1.96 2
mu = 69.3; sigm si gma a = 1. 1.96 96; ; % How many are no taller than 68 inches ? b1 = 68; p1 = (1+erf (1+erf((b1-mu ((b1-mu)/(sigm )/(sigma*sqrt a*sqrt(2))))/ (2))))/2 2
Chen CL
% How many are within 3 inches of the mean ? a2 = 66.3; b2 = 72.3; p2 = (er (erf(( f((b2-m b2-mu)/ u)/(si (sigma* gma*sqr sqrt(2 t(2))). )))... .. - erf erf((a ((a2-mu 2-mu)/( )/(sig sigma*s ma*sqrt qrt(2)) (2))))/ ))/2 2 % ANS: p1 = 0.2536, p2 = 0.8741 p1 = 0.2536 p2 = 0.8741
26
Chen CL
27
Test Your Understanding T7.2-1 Suppose that 10 10 more more height measurements are obtained so that the following numbers must be added to to the preceding height table. Hei eigh ghtt Add dd.. da data ta 64..5 64
1
65..0 65
2
66..0 66
1
67..5 67
2
70..0 70
2
73..0 73
1
74..0 74
1
(a) Plot the scaled frequency histogram. (b) Find the mean and standa sta ndard rd deviatio deviation. n. (c) Use the mean and an d st stan anda dard rd de devi viat atio ion n to es esti tima mate te how ho w man anyy 20 20-y -yea earr-o -old ld men are no taller tal ler tha than n 69 in inch ches es.. (d (d)) Estim Estimat atee how ho w man anyy are be bettwee een n 68 and 72 inches tall. (ANS: µ = 69 69..4, σ = 2.14; 43 43% %; 63 63% %)
Chen CL
28
Sums and Differences of Random Variables If x and y are normally distributed with means µx and µy , and variances σx2 and σy2, and if u = x + y and v = x y, then
−
µu = µx + µy µv = µx
− µy
σu2 = σv2 = σx2 + σy2
Chen CL
29
Random Number Generation Uniformly Distributed Random Numbers rand
rand
ans = 0.6161
ans = 0.5184
Application Example: if rand < 0.5 disp(’heads’) else disp(’tails’) end
Chen CL
To generate same sequence:
30
rand(’state’,0) rand
rand(’state’,0) rand
ans = 0.9501
ans = 0.9501
rand
rand
ans = 0.2311
ans = 0.2311
s = rand(’state’) rand(’state’,s) rand
rand(’state’,s) rand
OR
ans = 0.6068
ans = 0.6068
Chen CL
31
Test Your Understanding T7.3-1 Use MATLAB to generate a vector y containing 1500 uniformly distributed random numbers in the interval [ 5, 15]. Check your results with the mean , min , and max functions.
−
Chen CL
32
Ex: Optimal Production Quantity You have recently taken a position as the engineer in charge of your company’s seasonal product, which is manufactured during the off-season. You want to determine the optimum production level. If you produce more units than you can sell, your profit will not be as large as it could be; if you produce too many units, the unsold units at the end of the season will hurt profits. A review of the company’s records shows that the fixed cost of production is $30, 000 per season, no matter how many units are made, and that it costs $2, 000 above the fixed cost to make one unit. In addition, past sales have fluctuated between 25 and 50 units per season, with no increasing or decreasing trend in the sales data. Your sales force estimates that you cannot raise the price above $4, 000 during the season. Assume also that at the end of the season all unsold units can be sold at $1, 000 each.
Chen CL
33
Solution:
The most reasonable model for the sales is a uniform distribution over the interval [25, 50].
loop over k: compute profit for each of the 26 production levels (25 50)
∼
loop over m: random number simulation to compute profit
n = 5000; % number of random simulations level = [25:50]; % initialize production level vector cost = 30000+2000*level; for k = 1:26 cum_profit = 0; for m = 1:n demand = floor(rand*(50-25)+26); % Round towards if demand >= level(k) % minus infinity
Chen CL
income = 4000*level(k); else income = 4000*demand+1000*(level(k)-demand); end profit = income - cost(k); cum_profit = cum_profit + profit; end expected_profit = cum_profit/n; p(k,1) = level(k); p(k,2) = expected_profit; end plot(p(:,1), p(:,2),’o’,p(:,1), p(:,2),’-’),... xlabel(’No. of units’), ylabel(’Profit ($)’)
34
Chen CL
35 4
x 10 3.8
3.6
3.4
3.2
) $ ( t i f o r P
3
2.8
2.6
2.4
2.2
2 25
30
35
40 No. of units
45
50
Chen CL
36
Test Your Understanding T7.3-2 In T7.3-1, what is the optimum production level and resulting profit if we sell unsold units at the end of the season at cost ($2, 000), instead of below cost ? (ANS: 50 units; profit = $46, 000)
Chen CL
37
Random Number Generation Normally Distributed Random Numbers
randn(n) randn( m, n)
⇒
y
× n ND random number, mean=0, SD=1 m × n ND random number, mean=0, SD=1 n
= σx + µ random
number, mean=µ, SD=σ
Chen CL
38
Test Your Understanding T7.3-3 Use MATLAB to generate a vector y containing 1, 800 random numbers normally distributed with a mean of 7 and a standard deviation of 10. Check your results with the mean and std functions. Why can’t you us the min and max functions to check your results ?
Chen CL
39
Functions of Random Variables y = bx + c µy = bµx + c σy =
|b|σx
Chen CL
40
Ex: Statistical Analysis and Manufacturing Tolerances Suppose you must cut a triangular piece off the corner of a square plate by measuring the distances x and y from the corner. The desired value of x is 10 inches, and the desired value of θ is 20o. This requires that y = 3.64 inches. We are told that measurements of x and y are normally distributed with means of 10 and 3.64, respectively, with a standard deviation equal to 0.05 inch. Determine the standard deviation of θ and plot the relative frequency histogram for θ.
Chen CL
41
Solution: θ = arctan(y/x) s = 0.05; % SD of x and y n = 8000; % number of random simulation x = 10+s*randn(1,n); y = 3.64+s*randn(1,n); theta = (180/pi)*atan(y./x); mean_theta = mean(theta) sigma_theta = std(theta) xp = [19:.1:21]; z = hist(theta, xp); yp = z/n; bar(xp,yp), xlabel(’theta (deg)’),... ylabel(’relative frequency’) 0.16
0.14
0.12
y c n e u q e r f e v i t a l e r
0.1
0.08
0.06
0.04
0.02
0 18.5
mean_theta = 20.0041 sigma_theta = 0.2700
19
19.5
20 theta (deg)
20.5
21
21.5
Chen CL
42
Interpolation x = [ 7, 9, 11, 12]; y = [49, 57, 71, 75]; x_int = [8, 10]; interp1(x,y,x_int)
o
Time
Temp ( F)
7 AM
49
9 AM
57
11 AM
71
12 noon
75
ans = 53 64
75
70
65
60
55
50
45 7
7.5
8
8.5
9
9.5
10
10.5
11
11.5
12
Chen CL
43
Interpolation Temperatures (oF) Time
Loc.1 Loc.2 Loc.3
7 AM
49
52
54
9 AM
57
60
61
11 AM
71
73
75
12 noon
75
79
81
x = [ 7, 9, 11, y(:,1) = [49, 57, 71, y(:,2) = [52, 60, 73, y(:,3) = [54, 61, 75, x_int = [8, 10]’; interp1(x,y,x_int) ans = 53.0000 64.0000
56.0000 65.5000
12]’; 75]’; 79]’; 81]’;
57.5000 68.0000
Chen CL
44
Two-Dimensional Interpolation x = [0, 1]; y = [0, 2]; z = [49, 54; 53, 57]; z = 49 53
54 57
interp2(x,y,z, .6, 1.5) ans = 54.5500
Chen CL
45
Linear Interpolation Functions y_int=interp1(x,y,x_int)
Used to linearly interpolate a function of one variable: y=f(x). Returns a linearly interpolated vector y_int at the specified value x_int, using data stored in x and y. z_int=interp2(x,y,z,x_int,y_int)
Used to linearly interpolate a function of two variables: z=f(x,y). Returns a linearly interpolated vector z_int at the specified values x_int,y_int , using data stored in x,y and z.
Chen CL
46
Cubic-Spline Interpolation yi(x) = a i(x
7
≤x≤9 9 ≤ x ≤ 11 11 ≤ x ≤ 12
− xi)3 + bi(x − xi)2 + ci(x − xi) + di
y1(x) = y2(x) = y3(x) =
Time
Temp (oF)
7 AM
49
9 AM
57
11 AM
71
12 noon
75
x
∈ [xi, xi+1]
−0.35(x − 7)3 + 2.85(x − 7)2 − 0.3(x − 7) + 49 −0.35(x − 9)3 + 0.75(x − 9)2 + 6.9(x − 9) + 57 −0.35(x − 11)3 − 1.35(x − 11)2 + 5.7(x − 11) + 71
Chen CL
47
Cubic-Spline Interpolation x = [ 7, 9, 11, 12]; y = [49, 57, 71, 75]; x_int = [7 :.01 :12]; y_int = spline(x,y,x_int); plot(x,y,’o’,x,y,’--’,x_int,y_int),... xlabel(’Time (hrs)’), ylabel(’Temperature (deg F)’),... title(’Temperature measurements at a specific location’),. axis([7 12 45 80]) Temperature measurements at a specific location 80
75
70 ) F g e 65 d ( e r u t a r e p 60 m e T
55
50
45 7
7.5
8
8.5
9
9.5 Time (hrs)
10
10.5
11
11.5
12
Chen CL
48
Polynomial Interpolation Functions x = [ 7, 9, 11, 12]; y = [49, 57, 71, 75]; [breaks,coeffs, m, n] = unmkpp(spline(x,y)) breaks = 7 9 11 coeffs = -0.3500 2.8500 -0.3500 0.7500 -0.3500 -1.3500 m = 3 n = 4
12 -0.3000 6.9000 5.7000
49.0000 57.0000 71.0000
Chen CL
49
Polynomial Interpolation Functions x = [ 7, 9, 11, 12]; y = [49, 57, 71, 75]; [breaks,coeffs, m, n] = unmkpp(pchip(x,y)) breaks = 7 9 11 coeffs = -0.1023 0.9545 -0.9920 2.9385 -0.0588 -0.8824 m = 3 n = 4
12 2.5000 5.0909 4.9412
49.0000 57.0000 71.0000
Chen CL
50
Polynomial Interpolation Functions y_est=interp1(x,y,x_est,’spline’)
Returns a column vector y_est that contains the estimated values of y that correspond to the x values specified in the vector x_est, using cubic spline functions. y_int=spline(x,y,x_int)
Computes a cubic-spline interpolation where x and y are vectors containing the data and x_int is a vector containing the values of the independent variable x at which we wish to estimate the dependent variable y. The result y_int is a vector the same size as x_int containing the interpolated values of y that correspond to x_int. [breaks, coeffs, m, n] = unmkpp(spline(x,y))
Computes the coefficients of the cubic-spline polynomials for the data in x and y. The vector breaks contains the x values, and coeffs is an m n matrix containing the polynomial coefficients. m is the number of polynomials and n is the number of coefficients for each polynomial.
×
Chen CL
51
Polynomial Interpolation Functions: 1D y_est=interp1(x,y,x_est,’method’)
This command specifies alternate methods. The default is linear interpolation. Available methods are: nearest - nearest neighbor interpolation linear - linear interpolation spline - piecewise cubic spline interpolation (SPLINE) pchip
- piecewise cubic Hermite interpolation (PCHIP)
cubic
- same as ’pchip’
Chen CL
52
Polynomial Interpolation Functions: 2D z_est=interp2(x,y,z,x_est,y_est,’method’)
This command specifies alternate methods. The default is linear interpolation. Available methods are: nearest - nearest neighbor interpolation linear - bilinear interpolation (or bilinear) spline - cubic spline interpolation (SPLINE) cubic
- bicubic interpolation
Chen CL
53
1D Interpolation: Grid Data
x = 0 : 1 : 4*pi; y = sin(x).*exp(-x/5); xi = 0 : 0.1 : 4*pi; y1 = interp1(x, y, xi, ’nearest’); y2 = interp1(x, y, xi, ’linear’); y3 = interp1(x, y, xi, ’spline’); y4 = interp1(x, y, xi, ’cubic’); plot(x,y,’ko’), axis([0 14 -0.4 1]) hold on plot(xi,y1,’b-’); plot(xi,y2,’r:’); plot(xi,y3,’LineStyle’,’-.’,’Color’,[0,0.40,0]); plot(xi,y4,’LineStyle’,’--’,’Color’,[0.50,0.23,0.13]); %plot( x, y,’o’, ... % xi,y1,’g-’, ... % xi,y2,’r:’, ... % xi,y3,’LineStyle’,’-.’,’Color’,[0,0.40,0], ... % xi,y4,’LineStyle’,’--’,’Color’,[0.50,0.23,0.13]); legend(’Original’,’Nearest’,’Linear’,’Spline’,’Cubic’) hold off
Chen CL
54 1
0.8
0.6
0.4
0.2
0
−0.2
−0.4 0
2
4
6
8
10
12
14
Chen CL
55 1
0.8
0.6
0.4
0.2
0
−0.2
−0.4 0
2
4
6
8
10
12
14
Chen CL
56 1
0.8
0.6
0.4
0.2
0
−0.2
−0.4 0
2
4
6
8
10
12
14
Chen CL
57 1
0.8
0.6
0.4
0.2
0
−0.2
−0.4 0
2
4
6
8
10
12
14
Chen CL
58 1
0.8
0.6
0.4
0.2
0
−0.2
−0.4 0
2
4
6
8
10
12
14
Chen CL
59 1 Original Nearest Linear Spline Cubic
0.8
0.6
0.4
0.2
0
−0.2
−0.4
0
2
4
6
8
10
12
14
Chen CL
60
2D Interpolation: Grid Data
[x, y ] = meshgrid(-3 : 1 : 3); [xi,yi] = meshgrid(-3 : 0.25 : 3); z = peaks(x, y); zi1 = interp2(x, y, z, xi, yi, ’nearest’); zi2 = interp2(x, y, z, xi, yi, ’bilinear’); zi3 = interp2(x, y, z, xi, yi, ’bicubic’); subplot(2,2,1); surf(x, y, z); axis tight; title(’Original’); subplot(2,2,2); surf(xi, yi, zi1); axis tight; title(’Nearest’); hold on subplot(2,2,2); plot3(x, y, z, ’ko’); hold off subplot(2,2,3); surf(xi, yi, zi2); axis tight; title(’Bilinear’); hold on subplot(2,2,3); plot3(x, y, z, ’ko’); hold off subplot(2,2,4); surf(xi, yi, zi3); axis tight; title(’Bicubix’); hold on subplot(2,2,4); plot3(x, y, z, ’ko’); hold off
Chen CL
61 Original
Nearest
4
4
2
2
0
0
−2
−2
−4
−4 2 0 −2
−2
0
2
2
0 −2
Bilinear
4
2
2
0
0
−2
−2
−4
−4 2 −2
−2
2
Bicubix
4
0
−2
0
0
2
2 0 −2
−2
0
2
Chen CL
62
subplot(2,2,1); subplot(2,2,2); subplot(2,2,3); subplot(2,2,4);
contour(x, y, z, 20); contour(xi,yi,zi1,20); contour(xi,yi,zi2,20); contour(xi,yi,zi3,20);
title(’Original’); title(’Nearest’); title(’Bilinear’); title(’Bicubic’);
Original
Nearest
3
3
2
2
1
1
0
0
−1
−1
−2
−2
−3 −3
−2
−1
0
1
2
3
−3 −3
−2
−1
Bilinear 3
2
2
1
1
0
0
−1
−1
−2
−2 −2
−1
0
1
2
3
1
2
3
Bicubic
3
−3 −3
0
1
2
3
−3 −3
−2
−1
0
Chen CL
63
2D Spline Interpolation Spline
[x, y ] = meshgrid(-3:1 :3); [xi,yi] = meshgrid(-3:0.25:3); z = peaks(x, y); zi4=interp2(x,y,z,xi,yi,’spline’); surf(xi, yi, zi4); axis tight; title(’Spline’); hold on plot3(x, y, z, ’ko’); hold off
5
0
−5 3 2 1
2 0
1 0
−1
−1
−2 −3
−2 −3
Chen CL
64
2D Interpolation: Scatter Data
x = 6*rand(100,1)-3; % uniform distribution in -3,3 y = 6*rand(100,1)-3; z = peaks(x, y); [xi,yi] = meshgrid(-3:0.2:3, -3:0.2:3); zi = griddata(x, y, z, xi, yi); close all mesh(xi, yi, zi); hold on plot3(x, y, z, ’ko’); hold off axis tight; hidden off
Chen CL
65
6
4
2
0
−2
−4
3 2
3
1
2 0
1 0
−1 −1
−2
−2 −3
−3
Chen CL
Ex: Application to Robot Path Control
A robot arm having two joints: (a) Dimensions and arm angles (b) The hand’s path is not a straight line, but a complicated curve
66
Chen CL
67
The hand’s coordinates (x, y) xelbow = L1 cos θ1 xelbow
yelbow = L1 sin θ1
x = L1 cos θ1 +L2 cos(θ1 + θ2) y = L1 sin θ1 +L2 sin(θ1 + θ2)
⇒
yelbow 2 2
R2 = x + y
cos θ2 = cos β = α = θ1 =
R2 −L21 −L22 2L1 L2 2 R +L21 −L22 2L1 R arctan yx
α + β if θ2 < 0 α β if θ2 0
−
≥
If we use a cubic polynomial to express the joint angles as functions of time for 0 t T , then we can specify four conditions for each angle. Two of these conditions should require the polynomial to pass through the starting value θ(0) and the ending value θ(T ). The other two conditions require that the slope of the polynomial should be zero at the start and finish because we want the robot to start from rest and to finish at rest. The cubic polynomial that satisfies these
≤ ≤
Chen CL
68
conditions is
θ(t) = at3 + bt2 + θ(0) a = 2[θ(0) θ(T )]/T 3 b =
Example: L1 = 4, L2 = 3 feet, x(0) = 6.5, y(0) = 0 x(2) = 0, y(2) = 6.5 Solution: θ1(0) = 18.717o, θ2(0) = 44.049o; θ1(2) = 71.283o, θ2(2) = 44.049o θ1(t) = 22.5t3 + 67.5t2 18.717; θ2(t) = 44.049
− −
− −3[θ(0) − θ(T )]/T 2 ⇒
−
Suppose we want to control the arm path to be a straight line connecting the y −y starting and ending hand positions (y = y 0 + xf −x00 (x x0)). These points are f called knot points . To obtain smooth motion, we want the hand to pass through these points without stopping or changing speed, so we use cubic splines to interpolate between these points.
−
Write a MATLAB program to compute the arm angle solution for three knot points. Write another program to compute the splines required to generate three knot points and to plot the path of the robot’s hand. Do this problem for the case where L1 = 4, L2 = 3, (x0, y0) = (6.5, 0), (xf , yf ) = (0, 6.5).
Chen CL
69
% Solution for joint angles using n knot points L1=4; L2=3; % Enter the arm lengths, (x0,y0), (xf,yf), and x0=6.5; y0=0; xf=0; yf=6.5; n=4; % number of knot points n % Obtain the points on a straight line from (x0,y0) to (xf,yf) x = linspace(x0,xf,n+1); y = ((yf-y0)/(xf-x0))*(x-x0)+y0; R = sqrt(x.^2+y.^2); % Begin the angle solution (in degrees) theta2 = acos((R.^2-L1^2-L2^2)/(2*L1*L2))*(180/pi); beta = acos((R.^2+L1^2-L2^2)/(2*L1*R ))*(180/pi); alpha = atan2(y,x)*(180/pi); if theta2 < 0 theta1 = alpha + beta; else theta1 = alpha - beta; end theta1, theta2 theta1 = -28.5996
-10.1647
16.4004
42.9654
61.4004
theta2 = 44.0486
86.6409
99.2916
86.6409
44.0486
Chen CL
70
% Robot path using splines with three knot points % Define the joint angles and times along the straight line path theta1 = [-18.7170, -17.2129, 4.8980, 35.9172, 71.2830]; theta2 = [ 44.0486, 86.6409, 99.2916, 86.6409, 44.0486]; t_i = linspace(0, 2, 200); % Use 200 points for interpolation theta1_i = spline(t, theta1, t_i); theta2_i = spline(t, theta2, t_i); x_elbow = [4*cos(theta1_i*(pi/180))]; % Compute the (x,y) y_elbow = [4*sin(theta1_i*(pi/180))]; % coordinates of the elbow x = x_elbow + 3*cos((theta1_i+theta2_i)*(pi/180)); % Compute (x,y) y = y_elbow + 3*sin((theta1_i+theta2_i)*(pi/180)); % of the hand x1=[0, x_elbow(1), x(1) ]; y1=[0, y_elbow(1), y(1) ]; % Compute x2=[0, x_elbow(25), x(25) ]; y2=[0, y_elbow(25), y(25) ]; % arm’s x3=[0, x_elbow(50), x(50) ]; y3=[0, y_elbow(50), y(50) ]; % positio x4=[0, x_elbow(75), x(75) ]; y4=[0, y_elbow(75), y(75) ]; % to x5=[0, x_elbow(100), x(100)]; y5=[0, y_elbow(100), y(100)]; % display x6=[0, x_elbow(125), x(125)]; y6=[0, y_elbow(125), y(125)]; x7=[0, x_elbow(150), x(150)]; y7=[0, y_elbow(150), y(150)]; x8=[0, x_elbow(175), x(175)]; y8=[0, y_elbow(175), y(175)]; x9=[0, x_elbow(200), x(200)]; y9=[0, y_elbow(200), y(200)];
Chen CL
% Plot the results % plot(x,y, x1,y1, x2,y2, x3,y3, x4,y4, x5,y5),... plot(x1,y1,’Color’,[1,0,0],’LineWidth’,2) axis([0 7 -2 7]),... title(’Path of robot hand’),... xlabel(’x (feet)’), ylabel(’y (feet)’) hold on plot(x, y, ’--’, ’Color’,[0.5,0.5,0.5]) plot(x2,y2,’Color’,[0.,.5,0.],’LineWidth’,2) plot(x3,y3,’Color’,[0.,0.,1.],’LineWidth’,2) plot(x4,y4,’Color’,[1.,.5,0.],’LineWidth’,2) plot(x5,y5,’Color’,[1.,0.,1.],’LineWidth’,2) plot(x6,y6,’Color’,[0.,.5,1.],’LineWidth’,2) plot(x7,y7,’Color’,[1.,.5,.5],’LineWidth’,2) plot(x8,y8,’Color’,[.3,.5,.6],’LineWidth’,2) plot(x9,y9,’Color’,[.5,0.,0.],’LineWidth’,2) hold off
71
Chen CL
72
Robot Path Control Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7
Chen CL
73
Robot Path Control Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7
Chen CL
74
Robot Path Control Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7
Chen CL
75
Robot Path Control Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7
Chen CL
76
Robot Path Control Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7
Chen CL
77
Robot Path Control Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7
Chen CL
78
Robot Path Control Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7
Chen CL
79
Robot Path Control Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7
Chen CL
80
Robot Path Control Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7
Chen CL
81
Robot Path Control Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7
Chen CL
82
Animation %%%% Animation: Robot Arm % Robot path using splines with three knot points % Define the joint angles and times along the straight line path theta1 = [-18.7170, -17.2129, 4.8980, 35.9172, 71.2830]; theta2 = [ 44.0486, 86.6409, 99.2916, 86.6409, 44.0486]; t = [0, 0.5, 1.0, 1.5, 2.0]; t_i = linspace(0, 2, 200); % Use 200 points for interpolation theta1_i = spline(t, theta1, t_i); theta2_i = spline(t, theta2, t_i); x_elbow = [4*cos(theta1_i*(pi/180))]; % Compute the (x,y) y_elbow = [4*sin(theta1_i*(pi/180))]; % coordinates of the elbow x = x_elbow + 3*cos((theta1_i+theta2_i)*(pi/180)); % Compute (x,y) y = y_elbow + 3*sin((theta1_i+theta2_i)*(pi/180)); % of the hand % Plot the initial position and the desired path xx=[0, x_elbow(1), x(1)]; yy=[0, y_elbow(1), y(1)]; plot(xx,yy,’Color’,[0,0,0],’LineWidth’,2); axis([0 7 -2 7]),... title(’Path of robot hand’),... xlabel(’x (feet)’), ylabel(’y (feet)’)
Chen CL
hold on plot(x,y,’--’,’Color’,[0.5,0.5,0.5]) % abimation step = 20; for i = step:step:200 xx=[0, x_elbow(i), x(i)]; yy=[0, y_elbow(i), y(i)]; c = [0.005*i,0,1-0.005*i]; plot(xx,yy,’Color’,c,’LineWidth’,2); drawnow end hold off
83
Chen CL
84
Robot Path Control: Animation Path of robot hand 7
6
5
4
) t e e f ( y
3
2
1
0
−1
−2 0
1
2
3
4 x (feet)
5
6
7