Beginning Programming for Engineers Introduction to Programming and Computer Science.

35
Beginning Programming for Engineers Introduction to Programming and Computer Science

Transcript of Beginning Programming for Engineers Introduction to Programming and Computer Science.

Page 1: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Beginning Programming for Engineers

Introduction to Programming and Computer Science

Page 2: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Course Goals

• Learn basic concepts of computer science• Learn how to use Matlab effectively• Learn how to program in Matlab

Page 3: Beginning Programming for Engineers Introduction to Programming and Computer Science.

What is Programming?

There are 5 steps to successful programming:

1.Make sure you understand the problem.  The problem must be well-defined.

2.Find or develop an algorithm to solve the problem.3.Translate the algorithm into a language the computer can

execute.  (This translated algorithm is the program.)4.Run your program, to get the results.5.Verify the output, to make sure your program works

correctly.

Page 4: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Algorithms

An algorithm is a sequence of instructions that solves a problem, such that: • Each instruction is unambiguous, and is something the

computer can do.• After an instruction is finished, there is no ambiguity about

which instruction is executed next.• Execution finishes in a finite number of steps.

Page 5: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Describing Algorithms

1. Get a2. Get b3. Calculate 4. Display c

• Algorithms can be represented using either pseudocode or flowcharts.

• The computer program is also an expression of the algorithm.

• Frequently there is more than one algorithm that can solve a problem.

Page 6: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Diagram of a computer

• Input is data that flows into the computer, through an input device.

• Output is data that flows out of the computer, through an output device.

• The CPU transforms data, processing a simple machine language.

• The memory holds both data and the program.

Page 7: Beginning Programming for Engineers Introduction to Programming and Computer Science.

High Level Languages

We can use the computer to help us program it!• Source code is written by the

programmer in a high level language.

• A compiler translates source code into object code (machine language).

• An interpreter processes source code without translating to object code.

Page 8: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Development cycle

Page 9: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Programming, Computer Science, and Software Engineering• Programming: Applying the development cycle to solve

problems.• Computer science: Study of how to evaluate and develop

efficient algorithms for various computer architectures to solve various sorts of problems, as well as developing new computer architectures to enable more efficient algorithms.

• Software engineering: Primarily concerned with the methodology of crafting reliable and maintainable programs, documentation, etc.

• Domain expert: Expert in some field of application, but able to converse intelligently with the computing professionals.

Page 10: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Program Speed

• Every computer instruction takes time to execute.• An algorithm that can be completed with fewer instruction

executions will be faster than an algorithm that requires more instruction executions.

• Shorter programs are not necessarily faster than longer programs, because programs often "iterate" over groups of instructions.

Page 11: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Moore's Law

• Every two years, the number of transistors in an integrated circuit can double.o Until 2005: New computers

doubled in speed every 18 months.

o Since 2005: New computers have doubled the CPU cores every 18 months, but the CPU cores have not gotten faster.  (This is due to thermal issues: faster CPUs run too hot and self-destruct.)

Quad-core AMD processor die

Page 12: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Origins of Matlab

• Matlab was created around 1980 to allow students to work with matrix software without learning Fortran, etc.

• Mathworks, Inc. has further developed Matlab.

• Now widely used for engineering and science. Cleve Moler

Page 13: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Using Matlab

•  Matlab has features like:o Command line and historyo Workspace windowo Built-in editoro Built-in debuggero Help!

• Matlab needs access to a license server.

Page 14: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Alternatives to Matlab

• GNU Octaveo Programs can be written that work in both Matlab and

Octave.o Lacks the development environment and toolboxes of

Matlab.o Completely free – no license server!

• Other similar systems exist, such as Freemat and Scilab.

Page 15: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Matlab as a calculator

Page 16: Beginning Programming for Engineers Introduction to Programming and Computer Science.

MATLAB and Trig Functions

Try these computations:

sin(90)sin(pi/2)cos(pi/4)sin(pi/4)tan(pi/4)

sind(90) cosd(90) tand(90)

What units do these functions expect?

Page 17: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Variables and Memory Objects

Type in these expressions: ang = pi/4 c = cos(ang) s = sin(ang) c^2 + s^2• Notice how variables are

assigned values and used.

• Watch the "memory objects" in the Workspace window.

Page 18: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Clearing memory and the command windowYou can access variable values through the workspace window, or by typing in the name: c ang

 Issue this command.  Observe the workspace window:

clear

You can clear the command history window:

clc

Page 19: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Suppressing Output

Try these expressions:  ang = pi/4; c = cos(ang); s = sin(ang); c^2 + s^2; ans

What seems to be the result of ending lines with semicolons?

Page 20: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Simple Operations on Vectors

Try these expressions:  a = [ 1 2 3 ] a+a 5*a a*a a .* a a' a * a' a-3 a/2 2\a Last expression is "left division".

Page 21: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Simple Operations on Vectors (2)

Try these expressions:

a b = [ 2 ; 3 ; 4] a*b b = [ 5 6 7]

Page 22: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Using subscripts

Try these expressions:

a = [10 20 30 40 50] a(1) a(4) a(12/4) a(9) a(end)

The expression in parenthesis is a subscript or index.

We can assign into subscripted elements of vectors.  The vector will grow as needed.  Try these:  z(4) = 42 z(2) = 9 z(5) = 88 z(end) = 94 z(end+1) = 87

Page 23: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Entering Matrices

Try these expressions:

a = [ 1 2 3 4 5 6 ]

b = [10 20 ; 30 40; 50 60]

a*b

Page 24: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Subscripts and Matrices

Try these commands: a = [ 1 2 ; 3 4]a(1,2) = 9a(3,2) = 8

• Normally, use (row,column)• Single subscript counts down

column, then proceeds to next column...

Page 25: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Simple Ranges

Try these expressions:  1:10 0:10:50 50:-5:15

Page 26: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Simple Functions on Vectors

Try these expressions:  theta = 0:10:180; c = cosd(theta); s = sind(theta); theta(4) c(4)^2 + s(4)^2

Page 27: Beginning Programming for Engineers Introduction to Programming and Computer Science.

The plot command

Using the results in c, s from the last slide, try this command:

plot(c,s);

Page 28: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Writing Matlab scripts

• Sequences of commands can be saved to a script or “m-file”.

• Comments start with % or %% symbols.

• Long lines can be continued using …

Page 29: Beginning Programming for Engineers Introduction to Programming and Computer Science.

A simple script, simple_plot.m% This plots cos(theta), sin(theta) for theta% starting at 0 to 180 degrees, in increments of 10 % degrees.%% Programmed by R. Lindsay Todd

%% Clear memory, etc. clearclc

%% Computations theta = [ 0 10 20 30 40 50 60 70 80 90 100 110 120 ...          130 140 150 160 170 180 ];c = cosd(theta);s = sind(theta);

%% Plot plot(c,s);

Page 30: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Running a script

• To run a script, just type its name.• Alternatively, use the "run" button on the editor window.

Page 31: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Scripted input and output

% pythag.m: Get a, b and calculate c.%% Programmed by R. Lindsay Todd clearclc

%% Get the valuesa = input('Enter a:');b = input('Enter b:');

%% Do the calculationc = sqrt(a^2 + b^2);disp('The hypotenuse has been calculated.  It is:');disp(c);

• Use input to get values.• Use disp to print messages.

Page 32: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Simple functions

function pythagf(a, b)    % PYTHAGF calculates the hypotenuse of a triangle.    %    % The pythagf function uses the pythagorean theorem.

    % Programmed by R. Lindsay Todd

    %% Calculate    c = sqrt(a^2 + b^2);        %% Show result    disp('Calculated hyptenuse is');    disp(c);    end

Page 33: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Arguments and Parameters% Defining pythagf  (in pythagf.m)function pythagf(a, b)    c = sqrt(a^2 + b^2);       disp('Calculated hyptenuse is');    disp(c);end

% Calling pythagff = 30;pythagf(f, 40);

• The variables a and b are parameters of pythagf.

• The values 30 and 40 are arguments to the function pythagf.

• Notice we do not use inside pythagf to get the values of the parameters.

Page 34: Beginning Programming for Engineers Introduction to Programming and Computer Science.

Writing a function

• The function must go into an m-file with the same name as the function you are defining.  E.g., the function foo_bar must be defined in the file foo_bar.m

• The Matlab "path" determines where Matlab will look for scripts and functions.

• A common pitfall is to create a script or file whose name conflicts with the name of a Matlab function that your program needs.  Ways to avoid this:o Use names that are rather long.o Use names that can not possibly conflict with Matlab

names, e.g. "homework1".o Begin names with your initials, e.g., rlt_plot instead of plot

• The help command uses comments for its text.

Page 35: Beginning Programming for Engineers Introduction to Programming and Computer Science.

More on plotting

• The figure command can group related graphics and set some attributes for all the graphics.

• The hold on command prevents the figure from being cleared and redrawn for each plot.

• The axis command can set the range of graphics shown, the size of the window, tick-marks, etc.

• Use help to get more information!

figure('Color', 'w');  % White backgroundhold on;               % Don't clear... axis([0 10 -5 5]);     % 0<=x<=10, -5<=y<=5axis manual;           % Use my size!