% Author: Spike
% Date: 11/3/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lab = input('Please
enter the lab mark as a percent [1-100] ');
exam = input('Please
enter the exam mark as a percent [1-100] ');
competent =
input('Did the student complete all competency exercises [y/n]? ','s');
initialTotal =
(lab+exam)/2;
if
initialTotal>39
if ~ strncmp(competent,'yes',1)
finalTotal = 39;
elseif lab<40
finalTotal = 39;
elseif exam<40
finalTotal = 39;
else
finalTotal = initialTotal;
end;
else
finalTotal = initialTotal;
end;
fprintf('The final
mark for the subject is %5.1f%%\n',finalTotal);
if
finalTotal~=initialTotal
fprintf('\t Reset from %5.1f%% due to
failure of a component\n',initialTotal);
end;
21.9 SWITCH
• Switch statement
used for multiple selection upon a single expression
• Use when can
explicitly enumerate the options
• Can always be
implemented as an IF-ELSEIF construct
• General form:
switch expression
case test_expression1
statement(s)_1;
case
{test_expression2,...,test_expressionN}
statement(s)_2;
:
:
case test_expressionM
statement(s)_L;
otherwise
statement(s)_L+1
end;
• Expression must
either be a scalar or a string
- equality used for checking if a
scalar value
- strcmp() if strings
• First match and
corresponding statements executed
• otherwise is catch
statement (if no previous match)
21.10 Example –Switch
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% switcher.m
% An example of the use of the
Switch-Case
% statement. Converts from one set
of units
% of length to a distance in metres.
|
% Author: Spike
% Date: 11/3/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('UNITS OF
DISTANCE CONVERSION PROGRAM');
original =
input('Please input the distance [e.g., 7.6] ');
units =
input('Please input the units it was measured in ','s');
converted=1;
switch lower(units)
case {'cable','cables'}
metres = original*219.46;
case {'fathom','fathoms'}
metres = original*1.83;
case {'miles','mile','nautical
mile','nautical miles'}
metres = original*1852;
otherwise
fprintf('Unknown unit: %s, cannot
convert\n',units);
converted=0;
end;
if converted==1
fprintf('%.2f %s is %.2f
metres\n',original,units,metres);
end;
21.11 Review
• Motivation for
selection statements
• Simple IF
• IF-ELSE
• IF-ELSEIF…
• Nested Ifs
• Truth Tables
• Switch/Case
22 LOOPS IN MATLAB
• Iteration
(looping) has a role in all but a handful of all programming languages
- vital to
repetitively perform some task
• Iteration falls
into two major classes:
definite: a
countable number of times
indefinite: until
some condition is met
• Today’s lecture
considers the implementation of loops in Matlab
- FOR loops
- WHILE loops
- BREAK statement
References: For Engineers (Ch. 1, 7)
Mastering
(Ch. 13)
Student
(Ch. 11)
22.1 Motivation
• Looping is a vital
tool in solving most problems by computer:
- allows the repetition of task
without the repetition of code
• Examples include
- standard
user-terminated code
repeatedly
obtain user input
perform associated action
until user finished
(selected quit option)
- error checking
obtain user input
while input not
valid
print warning message
obtain a new input
- repetitive
processing of values
for each user
supplied value
process current result
get a new value
produce
summary/report
22.2 Definite Iteration (FOR Loop)
• Loop a countable
number of times
- number of times
known at loop initiation, cannot be modified once started
- counter variable
takes on new value each time through the loop
- guaranteed
termination
• Syntax:
statement_before;
for counter_variable = array
statement(s)_inside;
end;
statement_after;
• For example:
for cnt=1:10
fprintf(‘%d
squared=%d\n’,cnt,cnt*cnt);
end;
•
<counter_variable> takes on value of each element (column) in array
successively
- array tends to be a row vector
- loop executes as many times as
there are elements (columns) in the array
22.3 FOR Loop Schematic
22.4 FOR Loop Example
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% forX.m
% An example of the usage of the FOR
% loop to find the mean, max and min
% of a set of numbers.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com % Note: In matlab this could be done
% without the use of a for loop.
|
% Author: Spike
% Date: 16/3/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('Program to
find the mean, maximum & minimum');
disp('of a sequence
of numbers.');
disp(' ');
num = input('Please
input the number of values ');
if num>=1
val = input('Please input the first value ');
maxVal = val;
minVal = val;
tally = val;
for cnt = 2:floor(num)
val = input('Please input the next value
');
if val>maxVal
maxVal = val;
elseif val<minVal
minVal = val;
end;
tally = tally + val;
end;
fprintf('Mean=%f, max=%f, min=%f\n',...
|
tally/num,maxVal,minVal);
else
disp('Must have a positive number of
values');
end;
22.5 FOR Loop Additional
• Array is usually a
vector created such as 1:n. However consider:
>> A = [1 2 3;
4 5 6]
A =
1
2 3
4
5 6
>> for cnt=A
disp(cnt);
end;
1
4
2
5
3
6
• Note the
indentation style
• Modifying the loop
counter inside the loop is legal but non-sensical and should not be done
• Loops can be nested:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Creates a dome,
peak at (5,5)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for row=1:10
for column=1:10
height(row,column)=100-((row-5)^2+(column-5)^2);
end;
end;
22.6 Indefinite Iteration (WHILE Loop)
• Loop an indefinite
number of times:
- while a boolean condition
returns true
- zero through to infinite loop:
number of iterations generally unknown at inception
- test evaluated at top of loop
• Syntax:
statement_before;
while test_condition
statement(s)_inside;
end;
statement_after;
• For example:
count = 0;
fprintf(‘Before Loop x=%f,
y=%f\n’,…
x,y);
while x<y
x = 5*x^2 –
12.1*x + 27;
y = 2*y;
count = count +
1;
end;
fprintf(‘After %d iterations,
x=%f, y=%f\n’,…
count,x,y);
22.7 WHILE Loop Schematic
22.8 WHILE Loop Examples
% Program that loops
till user doesn’t require
% anymore.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
continue = ‘yes’;
while
strnncmp(continue,’y’,1)
x=input(‘Please enter a value
‘);
fprintf(‘f(%f)=%f\n’,x,someFunction(x));
continue = input(‘Would you
like to apply the function again [y/n]? ‘,’s’);
end;
% Guard on a user
input to ensure it falls
% within a
reasonable range.
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
velocity=input(‘Please
enter a velocity for the aircraft ‘);
while velocity<0
| velocity>10000
disp(‘Only positive velocities up to
10,000 km/hr accepted’);
velocity=input(‘Please enter an
acceptable velocity for the aircraft ‘);
end;
% Loops to build a
vector who’s elements
% monotonically
increase by pi/8 until cosine
% returns a negative
value. Note there is no
% need to check all
elements of the vector, but
% for illustration
purposes that is what is
% happening each
time at the top of the loop
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
vec(1) = 0;
while cos(vec)>=0
vec(end+1)=vec(end)+pi/8;
end;
disp(‘Final vector is:’);
disp(vec);
22.9 WHILE vs IF
• It is important to
appreciate the differences between IF & WHILE and employ the correct
structure in the correct circumstances:
- IF executes the code once (if
the condition is true) & continues with execution
- WHILE continues to execute the
code between the WHILE & END statements until the condition becomes
false.
|
22.10 General Loops & BREAK
• Matlab provides
the break statement to allow exit from a loop at an arbitrary location
• An infinite loop
may be written easily by employing a WHILE loop with a boolean condition that
is always true
- In Matlab the value 1 is treated
as true, while 0 is false
while 1
disp(‘An infinite loop. Hit
<cntrl>-C to kill’);
end;
• Combining the
above two facts allows for loops which exit at any place
while 1
velocity=input(‘Please enter an
aircraft velocity [1-10,000] ‘);
if velocity>0 &
velocity<=10000
break;
end; % IF
disp(‘Unacceptable velocity for
the plane.’);
end; % WHILE
22.11 Break Schematic
statement_before;
while test
statement(s)_1;
if exit_condition
break;
end;
statement(s)_2;
end;
statement_after;
22.12 Combined (Major) Example
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% worms.m
% A simple script file to calculate
where a
% shell will land when the landscape
is not
% flat. Users input initial
statistics for the
% shell and also how
large (in metres) the 1D
% terrain is. The
terrain is randomly generated
% then a loop
employed to track the shell at
% intervals of 0.1
seconds until it hits the
% ground or goes out
of range of the terrain
% generated.
|
% Author: Spike
% Date: 17/3/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%
% Grab the terrain
size
%%%%%%%%%%%%%%%%%%%%%%%%%%
while 1
length=input('Please input the length of
the landscape in metres ');
if length>0
length=ceil(length);
break;
end;
disp('Sorry, length must be positive');
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot the intial
Terrain
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
terrain =
makeTerrain(length);
plot(terrain);
xlabel('Horizontal
Distance (metres)');
ylabel('Height
(metres)');
title('Shell Shot on
Variable Terrain');
Example (Cont)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Safe input of
muzzle velocity
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while 1
muzzle=input('Please provide the muzzle
velocity in metres/sec ');
if muzzle>0
break;
end;
disp('Sorry, must be a positive velocity');
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Safe input of
barrel's inclination
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while 1
incline=input('Please input the angle of
the barrel relative to the horizon ');
if incline>0 & incline<180
break;
end;
disp('Angle must be between 0 and 180
degrees');
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set up constants
and explicitly handle the
% very first tenth
of a second.
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
timeStep = 0.1; % Snapshot 10 times per sec
gravity=9.8; % Acceleration due to gravity
currentTime=0.1; % Current elapsed time since
shot fired
initialHeight=1.0; % Height of barrel above ground.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com
xDelta=muzzle*cos(incline*pi/180)*timeStep;
% Constant
horizontal
% movement per timeStep
Example (Cont)
yVelocity=muzzle*sin(incline*pi/18
% Velocity in y
direction.
|
xloc=1+xDelta;
% Horizontal location of
shell
yloc=terrain(1)+initialHeight+yVelocity…
*currentTime-0.5*gravity*currentTime^2;
%
Vertical location of shell
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Main loop. While
we haven't run off the end of
% the terrain in
either direction. Check to see
% if we have hit the
ground. If not advance time
% by 1/10th % of a
sec and find the shell's new
% co-ordinates.
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while
round(xloc)>=1 & round(xloc)<=length
if yloc<terrain(round(xloc)) % HIT the ground!
text(xloc,terrain(round(xloc)),'Bang');
% mark on the
map
break; %
Quit loop
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Advance time and find new co-ordinates
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
currentTime=currentTime+timeStep;
xloc=xloc+xDelta;
yloc=terrain(1)+initialHeight+yVelocity*currentTime-0.5*gravity*currentTime^2;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Finished loop.
Hence shell either hit ground
% or flew off edge
of the map. Determine which
% and print an
appropriate message
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if round(xloc)>=1
& round(xloc)<=length
fprintf('At %5.1f seconds the shell
impacted at co-ordinates (%5.1f,%5.1f)\n',currentTime,xloc,yloc);
else
fprintf('At %5.1f the shell was at
(%5.1f,%5.1f) and left the terrain\n',currentTime,xloc,yloc);
end;
22.13 Worms Run
>> worms
Please input the
length of the landscape in metres 1000
Please provide the
muzzle velocity in metres/sec 100
Please input the
angle of the barrel relative to the horizon 60
At 17.5 seconds the shell impacted at
co-ordinates (876.0, 15.9)
>> diary off
22.14 Loop Usage Guidelines
• Should use most
appropriate loop construct for the particular problem at hand
while loop
- most general form of loop
- use for indefinite iteration
- can control number of executions
by appropriate execution
- generally easy to read/understand
for loop
- used for definite iteration
- easy to read
- can always be implemented as a
while loop
break & general
loop
- should generally be avoided
(preferentially employ while)
- use if structure of problem
demands such
- often hard to read/understand
(multiple exits)
22.15 Loop Control
• three aspects to
loop control for any loop:
• Initialisation of loop
parameter(s)
- automatic in a FOR loop
- before a WHILE loop
- before a general loop or before
the exit test
• Test
- automatic in a FOR loop
- WHILE: test for continuation
- GENERAL: test for termination
• Update loop parameter
- non-sensical in FOR loop
- must update in GENERAL &
WHILE loops
22.16 Common Types of Loops
• Certain styles of
loop construct are used repetitively due to their utility:
Sentinel Guarded
- used when an unknown number of
items are to be entered
- select a special value which the
user employs to indicate end-of-data
+ obviously special
value should not be a feasible input for processing
sentinel = -1;
val=input(‘Please
enter a positive value [-1 to exit]’);
while val~=sentinel
sum = sum+val;
val=input(‘Please enter a positive value [-1
to exit]’);
end;
Flag Guarded
- employ a boolean flag (variable)
to indicate termination
finished=0; % Our flag set to
false
while ~finished
<do some work>
if <desired event has happened>
finished=1;
end;
end;
22.17 Loops vs Implicit Vectorisation
• In most
programming languages loops are used to:
- iteratively process items (e.g.,
array contents)
- produce tables & charts
• Due to Matlab’s
implicit vectorisation loops are often unnecessary
- operations applied to entire
arrays in one statement
- vectorised I/O
• Lecture on
efficiency covers the issue in more detail
• Consider the
example used at the start of the lecture to illustrate FOR loops:
22.18 Loops vs. Vector Example
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% forX_alt.m
% An alternative to the FOR loop
% example showing Matlab's support
% for implicit vectorisation and hence
% that there is often no need for
% explicit looping.
|
Kami ada di Jakarta Selatan. KAMI MEMBERIKAN KURSUS MATLAB ONLINE - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Kami membuka kursus Matlab untuk pemula dan mahasiswa atau insinyur yang ingin memperdalam Matlab dan menerapkan dalam bidang teknikal, engineering, rekayasa, dsb. Format bimbingannya tugas-tugas yang bisa membantu Skripsi, Tesis, DISERTASI
Bimbingan dilakukan secara online bisa lewat WA atau email Dijamin Bisa, atau bisa mengulang kembali. Kami juga dapat membantumembuatkan aplikasi atau program matlab/lainnya. Anda akan dilatih oleh Tim Profesional - HUBUNGI MASTER ENGINEERING EXPERT (MEE) 081219449060. Email: kursusmatlab@gmail.com % Author: Spike
% Date: 16/3/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('Program to find
the mean, maximum & minimum');
disp('of a sequence
of numbers.');
disp(' ');
num = input('Please
input the number of values ');
if num>=1
disp('Please input the values now ');
values = input('enclosed by square
brackets- e.g., [1 67 87.4] ');
fprintf('Mean=%f, max=%f, min=%f\n',...
|
KURSUS MATLAB ONLINE Skripsi, Tesis, DISERTASI 081219449060
Selasa, 13 Januari 2015
KURSUS MATLAB ONLINE Skripsi, Tesis, DISERTASI 081219449060
Langganan:
Posting Komentar (Atom)
boleh minta contact numbernya..?
BalasHapus