eee244_2
eee244_2
FUNDAMENTALS
Scalars
• To assign a single value to a variable, simply type the variable
name, the = sign, and the value:
>> a = 4
a=
4
• Note that variable names must start with a letter, though they
can contain letters, numbers, and the underscore (_) symbol
Array Creation
% Matlab command to create a vector
>>x = [ 1 2 3 4 5]
ans =
12345
# Python command
import numpy as np
x=np.array([[1,2,3], [4,5,6], [7,8,9]])
x
Mathematical Operations
• Mathematical operations in MATLAB/Python can be
performed on both scalars and arrays
Matlab Python
Exponent 4^2 = 16 4**2 =16
Multiplication 2*8 = 16 2*8 = 16
and 32/4 = 8 32/4 = 8
Division
Generate p pi Import numpy as np
2*np.pi = 6.2832
np.pi/4 = 0.7854
x*y
x/y
x+y
x-y
A= 367 B=1 1
5 -3 0 2 1
3 -3
Matlab Python
A = [ 3 6 7; 5 -3 0] import numpy as np
B = [1 1; 2 1; 3 -3] A = np.array([[3, 6, 7], [5, -3, 0]])
C = A*B B = np.array([[1, 1], [2, 1], [3, -3]])
C = A.dot(B)
print(C)
Element-by-Element Calculations
• At times, you will want to carry out calculations item by item
in a matrix or vector. They are also often referred to as
element-by-element operations.
• For array operations, both matrices must be the same size
A= 367 B=1 11
5 -3 0 2 13
Matlab Python
A = [ 3 6 7; 5 -3 0] import numpy as np
B = [1 1 1; 2 1 3] A = np.array([[3, 6, 7], [5, -3, 0]])
C = A.*B B = np.array([[1, 1, 1], [2, 1, 3 ]])
C = A*B
print(C)
Graphics in Matlab/Python
• MATLAB/Python have a common plot command to graph
vectors
Matlab Python
x = [ 3 6 7] import numpy as np
y = [1 2 3] import matplotlib.pyplot as plt
plot(x,y) x = np.array([3,6,7])
y = np.array([1,2,3])
plt.plot(x,y)
plt.xlabel('x')
plt.ylabel('some numbers')
plt.show()
Other Matlab Plotting Commands
• hold on and hold off
– hold on will keep the current plot active
– Enables the user to superimpose plots on each other
– hold off will release the current plot
• subplot(m, n, p)
– subplot command enables multiple plots on a single page
– Divides the page into m x n sections
Loops in Matlab/Python
• IF and FOR loops in Matlab are completed with an
end command to complete the loop operation
# IF loop in Python
x=5
if x > 15:
print(“x > 15”)
elif x < 15:
print(“x < 15”)
For Loops
% Matlab
x=0
for i = 1:10;
x=x+i
end
# Python
x=0
for i in range(1,10):
x=x+i
print(x)