Sei sulla pagina 1di 39

Eilon Sharon, Weizmann 2008

Variables and Matrix Manipulation

Tutorial 2 and 3:

Introduction to Matlab
& Data Analysis

Learn Arrays Mathematical Operations

Learn Simple String Manipulations

Learn to Use Array Editor

Solving Linear System of Equations

Master Arrays manipulation

Introduce the Notion of Variables & Data Types.

Goals

Eilon Sharon, Weizmann 2008

Variables

Read it
Use it for computation / change its value
and save it back to memory

The identifier provides a reference to the


value such that your programs can:

The value is kept in the memory

1 1 0 0 0 1 0 1

A MATLAB variable is an identified piece of


data (= the assigned value)

Variables

clear;
clear all;

2. Case sensitive!!!

3. Cant be a keyword

Underscore

clear max_grade;

Digits

Assignment
operator

Value

1. Cant start with a number

Letters

Variable identifier (name):

max_grade = 100;

Variable Assignment

Consider the following:


x = 50;
disp = 100;
disp(x);
builtin(disp, x);
clear disp;
disp(x);
What happened?

Try to change grade value to 100.

Lets look at the workspace window.

Dont override built-in


functions!!!

The disp variable override the


disp built-in function

Define a variable grade and assign the value 80 to it.


Personal Factor - Now add to the grade its square root (there are
several options to solve this)
Define a classFactor and assign 10 to it.
Define a finalGrade variable and assign the value of the factored
grade plus the class factor to it.
What is the final grade?

Exercise 2:

Exercise 1:

Variable Hands On

locates a function or identify as variable

saves the workspace to a .mat file

loads variables from a .mat file into the workspace

Create some a,b,c variables


save(tutorial2.mat, a, b,c);
clear;
Load(tutorial2.mat)

Example:

load(file_name);

clear x;
save(file_name, var1, var2, )

which(linspace);

Workspace functions

Eilon Sharon, Weizmann 2008

Data Types

Everything in Matlab is an array!

Next lectures

A scalar is also an
array of size 1x1

Data Types (Variable types)

Default

Integer

10

Data Types (Variable Types)

Real(/Complex):
x = double(235.5);
x = single(235.5);
x = 235;

a = int16(100);
Be careful of
Memory overflow
b = int8(5000);

Integer:

Data types - Numeric

11

Help -> contents -> MATLAB ->


Programming -> Numeric Types ->
Function summary.

Is Not A
Number

isinf, isnan, floor, ceil

Notice:

A summery of numeric functions:

Infinite

Numeric Data Functions

12

Eilon Sharon, Weizmann 2008

Arrays Manipulation

13

a = [1 2 3 4];
b = [1, 2, 3, 4];
c = [1; 2; 3; 4];
d =1:1:4;
e = (1:4);

Which are equal?

operator- transpose (near the


enter key)

Colon operator from:step:to.


Default step is one.

New line / Semicolon new line

Space / comma New element


in same line

A one dimensional array is named vector


A two dimensional array is named matrix

Creating arrays

A Matlab variable is an array.

Arrays and Matrices

14

Min value

Max value

linspace(0,100,51);
Number of points

logspace(1,10,11);
Same, but logarithmically spaced
between 10^1 and 10^10

Why? Consider 0:0.33:1 or 0:0.08:1

linspace and logspace

15

hold off; plot(x,y,'b-'); hold on; plot(x,z,'r-'); legend('Sine', 'Cosine');

y = sin(x);
z = cos(x);

x = linspace(-pi,pi, 21);
% another way: x = (-1:0.1:1) * pi;

Compute y and z the sine and cosine function of x


respectively.
Draw a plot of the sine and cosine function of [-, ]
using the following code:

16

[,0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1,0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,]

Reminder:linspace
Use the commands we learned to define x as:

Drawing the Sine and Cosine Functions

ans = 3 3
See also: length(A) numel(A)

size(A)

A(2,3) <->A(8)

ans = 8

sub2ind(size(A), 2,3)

Subscripts to single index:

Getting the matrix size:

B(:, :, 1) = A;
B(:, :, 2) = A;
B(:, :, 3) = A;

1
4
7

Multi dimensional arrays:

A = [1, 2, 3; 4, 5, 6; 7, 8, 9]

2
5
8

3
6
9

2
5
8

3
6
9

B=
1
2
4 15 2
7 4 81 5
7 48
7

3
6 3
92 6 3
59 6
8
9

Third dimension
(Page)

A=
1
First dimension
4
(Row)
7

17

Second dimension
(Column)

Multidimensional Array Indexing

ans =
2
1
1
3
4
2

ans =
2
4
ans =
3
1

b = fliplr(a)

c = flipud(a)

The last coordinate


in the dimension

2
4

a(1,end:-1:1)

a(2)
a(:)

a % or a.
ans=
1
2
3
4

ans=
1
3
2
4

a = [1, 2; 3, 4]

Array flattening

a=
1
3

Arrays Manipulation

ans =
3

18

ans =
1

ans =
2 4
2 4

reshape(a,1,4)

repmat(e,2,2)

See also: diag()

g=
1

g = [d(1:3), e]

f=

e=
2

3
4

Horizontal Array
Concatenation

Vertical Array
Concatenation

d=
1

1
2

f = [d; e]

e = 2:2:10

d = 1:2:9

6
6

5
6

9
10

10

8 10 2
8 10 2

7
8

4
4

Arrays Manipulation More

6
6

8
8

10

10
10

19

>> A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
A=
1
2
3
4
5
6
7
8
9
>> A(3,4)
??? Index exceeds matrix dimensions.
>> A(4,4) = 10
A=
1
2
3
0
4
5
6
0
Notice the
7
8
9
0
difference!
0
0
0 10

1
4
7
0

2
5
8
0

3 0
6 0
9 0
0 10

1 2 3
4 5 6
7 8 9 ?

Assignment into Array

20

Subscripted assignment
dimension must match!

>> B = [21, 22, 23; 24, 25, 26]


B=
21 22 23
24 25 26
>> A(1:2,1:3) = B
A=
21 22 23
24 25 26
7
8
9

Scalar expansion

2
5
8

3
6
9
21 22 23
24 25 26

1
Notice the 4
difference! 7

>> A(1:2,1:3) = 10
A=
10 10 10
10 10 10
7
8
9

>> A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
A=
1
2
3
4
5
6
7
8
9
>> A(:) = 21:30
??? In an assignment A(:) = B, the
number of elements in A and B
must be the same.

Assignment into Array

21

Images are represented by


matrices
Lets use this to visualize
matrix manipulation
Andy Warhol style.

21
21
4
21
21

10
73
10
3
8

Example - Image Manipulation

10

18

10

22

21

45

21

21

21

zeros(10,10)
ones(10,10)
rand(10,10)
randn(10,10)
eye(10,10)
1
0
0

0
1
0

0
0
1

Identity matrix

Create a sample.

Allocate memory in
advance!

What is it good for?

Standard Arrays

23

>> A(is_larger_than5)
ans =
8
Array can be
9
indexed with
6
logical array!
7

>> class(is_larger_than5)
ans =
Logical

>> is_larger_than5 = A > 5


is_larger_than5 =
1 0 1
Logical
0 0 1
0 1 0 array

operator

>> A = magic(3)
A=
8 1 6
3 5 7
Logical
4 9 2

1
2
c=
1
2
3
3

find can return


subscripts

the # of output
parameters!

24

A([1 3 1 2], [1 2 3 3]) = 20

What is wrong?

>> index_larger_than5 = find(A>5)


index_larger_than5 =
1
6
Array of indices
7
8
>> A(index_larger_than5) = 10 % A(find(A>5))= 10
A=
10 1 10 Assignment
3 5 10 using indices
>> A(r,c) = 20
4 10 2 array
% wrong!
A=
>> [r c] = find(A>5)
20 20 20
r=
20 20 20
1 Matlab functions
20 20 20
3 output depends on

Find & logical Arrays

Try to run A(1:3,1:3) = ones(7,7); What did you get?

mean(A(4,:))

A = A(:,4:6); % or

A(:,1:3) = [];

A( find(A > 20) ) = 100;

A = magic(6)
A(:,:) = ones(7,7)
??? Subscripted assignment dimension mismatch.

Replace all element larger than 20 with the value 100


Now, make A be only its last three columns
Then compute the mean of the fourth row.

Consider the martix: A = magic(6);

Short Example

25

Eilon Sharon, Weizmann 2008

Arrays mathematical operations

26

A+B
A-B
-A
A.*B
A./B
A.\B
.^

Matrices dimensions
must match
+ * /\ by scalar are
element-wise

Element by element:

Search help for : Arithmetic Operators

x .* y'
x*y
y*x

x = 1:3;
y = x';

Try to run the following:

27

A #columns == B #rows

A^p

C = A*B :

Array arithmetic

70

60

1.05 1.07 0.99

77
1.10

65

Multiply each grade by the class participation score


Then add 10 points to all grades?

>> grades = [80 77 70 60 65];


>> participation_in_class = [1.10, 1.05, 1.07, 0.99, 1.10];
>> final_grades = (grades .* participation_in_class) + 10
final_grades =
98.0000 90.8500 84.9000 69.4000 81.5000

Answer:

We want to compute the final grade as follows:

1.10

Participation in class

80

Grade

Consider the following:

Grades Exercise Revisited

28

Eilon Sharon, Weizmann 2008

String Manipulations

29

I am a star!
ans = gnirts a ma I

[s([1:9,6,10]) '!']

s(end:-1:1)

30

Char arrays can be concatenated


like numerical arrays

>> a = 'It is easy ';


>> b = 'to concatenate strings!';
>> [a, b]
ans =
It is easy to concatenate strings!

s = I am a string
ans = I am

Strings are represented


as Char array
Assigning a string:
a=I am a string

Lets try it:


s=I am a string
s(1:4)

Strings as Char Arrays

>> ['pie value is: ' num2str(3.14157)]


ans = pie value is: 3.1416

>> class(d)
ans = double

>> d = str2num(c)
d = 3.1416

>> class(c)
ans = char

>> c = num2str(3.14157)
c = 3.1416

Are very useful


for output string
generation

str2num

num2str

Tip

31

Working with Strings Generating Output

>> size(str_mat)
ans = 3
5

>> class(str_mat)
ans = char

>> str_mat = ['one '


'two '
'three']
str_mat =
one
two
three

Rows length must be equal!


(a square matrix)

Concatenate vertically!

>> str_mat =
char('one','two','three')
str_mat =
one
two
Three

Working with strings char matrices

32

Compare the first n


characters of the two strings

>> strcmp('abcd','abc')
ans =
0
>> strncmp('abcd','abc',3)
ans =
1

Compare the strings

33

Working with Strings String Comparison

Eilon Sharon, Weizmann 2008

Array Editor

34

two = 2;
[One plus one is:' num2str(two)]

Omitting the ;
disp(helo world);
[Today we added num2str() ]
Example:

From: work space, open selection


Displays variables
Edit variables value
Copy-paste from Excel (grades example)

Array Editor:

Display:

Array Editor and Array Display

35

Eilon Sharon, Weizmann 2008

36

Solving Linear System of Equations

a13 x3 = b1
a23 x3 = b2
a33 x3 = b3

a12 x2
a22 x2
a32 x2

Ax=b

A=[1
1
1;1
2
3;1
3
6 ];
b = [3; 1; 4];
x = A\b;
Solution: x = 10
-12
5
More: search help solving linear equations 37

a11 x1

a21 x1
a x
31 1

Say we want to solve the following system:

Epilogue - Solving Linear Systems of Equations

x = A\b

Answer:
A = [1 2 3
456
7 8 0];
b = [366; 804; 351];

7x+8y = 351

4x+5y+6z= 804

1x+2y+3z = 366

25.0000
22.0000
99.0000

x=

Result:

Solve the following problem:

38

Epilogue - Solving Linear Systems of Equations

Learn Arrays Mathematical Operations

Learn Simple String Manipulations

Learn to Use Array Editor

Solving Linear System of Equations

Master Arrays manipulation

Introduce the Notion of Variables & Data Types.

Summary

39

Potrebbero piacerti anche