Industrial and Manufacturing Engineering Department: Programming
Industrial and Manufacturing Engineering Department: Programming
Engineering Department
Course instructor:
Mr. Shakeel Ahmed
(Assistant Professor)
Programming 2
• The most awful truth about computers is that they are all
dumb. Everything must be explicitly told. Spelling out the
most minor and obvious detail.
• Otherwise, you will either get a syntax error (computer not
understanding what you are saying) or a programming error
(the computer understanding what you are saying but it is
different from what you mean).
• There are many programing languages. Why use Matlab? As a
first programming language, it is great, it has simple syntax,
it is easy to get started with and easy to do graphics. While
other programming languages are faster running they are
slower to learn and to use.
1
The Command Prompt: 3
Getting Help 4
• help: should be used when you know a command name. e.g. help zeros
• Look for: can be used to find a command to perform a task e.g.
lookfor roots
• doc: same as help but opens help in a new window with more details
e.g. doc plot
• Exercise:
• Learn about the commands ones, zeros, sum, and diag.
• Learn about magic and verify what you learned with sum.
2
Simple Expressions 5
Using Variables 6
3
Referencing matrix elements 7
>> A
A=
1 2 3
4 5 6
7 8 9
A(2,2:3) = 10:11
A=
1 2 3
4 10 11
7 8 9
4
Exercise 9
2. Write an expression for the sum of the squares of the numbers from 1 to 10
3. Write an expression for the sum of the powers of 0.5 to the numbers from 1 to
10
Logical Constructs 10
>> 1==2
>> 3~=5
>> 5<=6
>> 7<=10
Boolean operations
1~=2 | 3<4
3~=4 & 8==(4+4)
~(2<=8)
5
Formatting Text 11
Examples 12
A1 = [9.9, 9900];
A2 = [8.8, 7.7 ; 8800, 7700];
formatSpec = 'X is %4.2f meters or %8.3f mm\n';
fprintf(formatSpec,A1,A2)
ans =
X is 9.90 meters or 9900.000 mm
X is 8.80 meters or 8800.000 mm
X is 7.70 meters or 7700.000 mm
%4.2f in the formatSpec input specifies that the first value in each
line of output is a floating-point number with a field width of four
digits, including two digits after the decimal point.
\n is a control character that starts a new line.
6
Example 13
Practice with the following code:
A = magic(4);