Wednesday, November 18, 2020

, , ,

fft matlab Function And ftt code with Example

 Fast Fourier transform of fft function in matlab.

Syntax:-

Y = fft(X)
Y = fft(X,n)
Y = fft(X,n,dim)

Discprition for fft matlab Function

If x is an vector then it will return the Fourier transform of that vector

Let x is an matrix then fft(X) assume the colum as a vactory and return Fourier transform of each column.

Now let assume X is an multidimensional array then fft(X) treats the values of first array dimension only if the size of that array is not equal to 1 as vector and gives the Fourier transform of each vector

Cases with the fft() MATLAB Function

Y = fft(X,n) returns the n-point DFT.

Case 1

X is an vector and the length of X is lower then n. X will be padded with trailing zeros to length n

Case 2

X is an vector and the length of X is Higher then n. X will be truncated to length n

Case 2

X is an matrix then each column of that matrix treated as in the vector case

Case 2

multidimensional array X is treated as like fft(X) the "first array dimension only if the size of that array is not equal to 1" treated as in the vector case

Y = fft(X,n,dim) gives the Fourier transform along with the dimension dim.



Example Code For ftt() function in MATLAB

Use the help of Fourier transforms to find the frequency components of a signal buried in noise.

Fs = 1000;            % Sampling frequency                    
T = 1/Fs;             % Sampling period       
L = 1500;             % Length of signal
t = (0:L-1)*T;        % Time vector
Form a signal containing a 50 Hz sinusoid of amplitude 0.7 and a 120 Hz sinusoid of amplitude 1. S = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t); Corrupt the signal with zero-mean white noise with a variance of 4. X = S + 2*randn(size(t)); Plot the noisy signal in the time domain. It is difficult to identify the frequency components by looking at the signal X(t). plot(1000*t(1:50),X(1:50)) title('Signal Corrupted with Zero-Mean Random Noise') xlabel('t (milliseconds)') ylabel('X(t)')
Compute the Fourier transform of the signal.

Y = fft(X);

Compute the two-sided spectrum P2. Then compute the single-sided spectrum P1 based on P2 and the even-valued signal length L.

P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);

Define the frequency domain f and plot the single-sided amplitude spectrum P1. The amplitudes are not exactly at 0.7 and 1, as expected, because of the added noise. On average, longer signals produce better frequency approximations.

f = Fs*(0:(L/2))/L;
plot(f,P1) 
title('Single-Sided Amplitude Spectrum of X(t)')
xlabel('f (Hz)')
ylabel('|P1(f)|')

Now, take the Fourier transform of the original, uncorrupted signal and retrieve the exact amplitudes, 0.7 and 1.0. Y = fft(S); P2 = abs(Y/L); P1 = P2(1:L/2+1); P1(2:end-1) = 2*P1(2:end-1); plot(f,P1) title('Single-Sided Amplitude Spectrum of S(t)') xlabel('f (Hz)') ylabel('|P1(f)|')

OUTPUT For Example of fft () matlab:-

fft () matlab output
fft () matlab output



fftshift matlab
fftshift matlab



fourier transform matlab
fourier transform matlab

Tuesday, November 17, 2020

, ,

Learn about the Matlab linspace function With Example

 Matlab linspace is used to Generate linearly spaced vector.

Syntax for Matlabn Linspace: -

y = linspace(x1,x2)
y = linspace(x1,x2,n)

  • y = linspace(x1,x2) give a row vector which is made with the 100 points with equal distance between x1 and x2
  • y = linspace(x1,x2,n) return the n number of points and these point keep the distance of (x2-x1)/(n-1).
  • This Matlab linspace function is very similar to the colon operator, “:” But linspace function in matlab direct control over the number of points and always include the endpoints.

Example of Matlab linspace


Create a vector of 100 evenly spaced points in the interval [-5,10]. 
y = linspace(-5,10);

Create a vector of 7 evenly spaced points in the interval [-5,7]. 
y1 = linspace(-5,7,7)

output

Example of Matlab linspace
  Example of Matlab linspace

Important points : -

  • x1 and x2 gives the interval for points which is generated by Matlab linspace.
  • Data Types: single | double | datetime | duration
    • Complex Number Support: Yes 



Monday, November 16, 2020

, , ,

Example program for super function in python

 super() function in python return the proxy object it's also a temporary object of the superclass and this object help us to access the method of base class.

Super function has two use :-

  • This function Working with Multiple Inheritance
  • Help us to avoid base class name explicitly

Example of super function in python:-

if it use single inheritance then this function help us to refer base class by super()
class Mammal(object):
  def __init__(self, mammalName):
    print(mammalName, 'is a warm-blooded animal.')
    
class Dog(Mammal):
  def __init__(self):
    print('Dog has four legs.')
    super().__init__('Dog')
    
d1 = Dog()

OUTPUT

Dog has four legs.
Dog is a warm-blooded animal.

We can also change the name of base class Let see

# changing base class to CanidaeFamily
class Dog(CanidaeFamily):
  def __init__(self):
    print('Dog has four legs.')

    # no need to change this
    super().__init__('Dog')

Well super function in python is an call method for base class via delegation and that is called indirection and this happen at run then time in between this time we can also use the other base classes at different times.

Example program for super() with Multiple Inheritance

class Animal:
  def __init__(self, Animal):
    print(Animal, 'is an animal.');

class Mammal(Animal):
  def __init__(self, mammalName):
    print(mammalName, 'is a warm-blooded animal.')
    super().__init__(mammalName)
    
class NonWingedMammal(Mammal):
  def __init__(self, NonWingedMammal):
    print(NonWingedMammal, "can't fly.")
    super().__init__(NonWingedMammal)

class NonMarineMammal(Mammal):
  def __init__(self, NonMarineMammal):
    print(NonMarineMammal, "can't swim.")
    super().__init__(NonMarineMammal)

class Dog(NonMarineMammal, NonWingedMammal):
  def __init__(self):
    print('Dog has 4 legs.');
    super().__init__('Dog')
    
d = Dog()
print('')
bat = NonMarineMammal('Bat')

OUTPUT

super function in python
Example program for super function in python

 

 

Method Resolution Order (MRO)For super() function in python

MRO is use to maintain the order at the persence of the multiple inheritance and ir can also view by using the __mro__ attribute.

>>> Dog.__mro__
(<class 'Dog'>, 
<class 'NonMarineMammal'>, 
<class 'NonWingedMammal'>, 
<class 'Mammal'>, 
<class 'Animal'>, 
<class 'object'>)

Saturday, November 14, 2020

, ,

Example program for setattr() function in Python

setattr() function in Python use to set the value of an attribute.

setattr() function
setattr() function in Python

 

Syntax : -

setattr(object, name, value)

If you want to read the object then use the getattr() function.

  • Parameters For setattr():- 

It takes three parameters and these are:-

  • Object : - the object whose value is going to be set in python program.
  • Name - set the name of attribute.
  • value - Desire value given to the attribute

setattr() function in python doesn't return the value.

Example program for setattr() function in Python

class Person:
    name = 'Adam'
    
p = Person()
print('Before modification:', p.name)

# setting name to 'John'
setattr(p, 'name', 'John')

print('After modification:', p.name)

Output:-

setattr() function in Python
program for setattr() function in Python


Thursday, November 12, 2020

, ,

Example for getattr() function in python

 getattr() function in python is sued to get the value of an object attribute and it return the default value if no attribute of that object is found.

getattr() function in python
Example for getattr() function in python

 

The reason of using getattr() function because it return the default value.Now let see the basic syntax : -

getattr(object_name, attribute_name[, default_value])

Example of getattr() function in python

this program will help you to teach about how to use the getattr() function in python

class Student:
    student_id=""
    student_name=""

    # initial constructor to set the values
    def __init__(self):
        self.student_id = "101"
        self.student_name = "Adam Lam"

student = Student()
# get attribute values by using getattr() function
print('\ngetattr : name of the student is =', getattr(student, "student_name"))

# but you could access this like this
print('traditional: name of the student is =', student.student_name)

Why use getattr() function

  • This function helps to get the object attribute value with the help of Name of that attr. or you can also manually set the input attribute name by console.
  • This function also give the freedom for set the default value according to your need.

Sunday, November 8, 2020

, ,

Example Program for delattr() function in python

Python delattr() function used to delete an attribute from an object.

Syntax For delattr :-

delattr(object, name)

delattr () Parameters in Pyhton

There two attribute which is used in Delattr () function in python:-

  • First one is object where name attribute is removed from that object

  • second one is name it can be string which is removed from the object.

  • delattr() function in python doesn't return any value.

Python getattr Example Program in python:-

class Coordinate:
  x = 10
  y = -5
  z = 0

point1 = Coordinate() 

print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)

delattr(Coordinate, 'z')

print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)

# Raises Error
print('z = ',point1.z)

OUTPUT : -

Program For delattr() function in python
Program For delattr() function


Saturday, November 7, 2020

, ,

Example Program for complie() function in python - Python Program

 

 The complie() function in python is used to return python code object from a source like (string,AST object,byte string).

Syntax For Complie(): -

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)


Well the return object from the compile function in python can be called by exec() and eval() method.

Parameter : -

  • A source that can be used in compile function that can be normal string, a byte string, or an AST object.

  • A code that can be read from a file. If it doesn't read form a file then you give a name according to you.
  • Either exec,eval or signal method can be used to call a function.
  • Well eval accept only a single expression.
  • exec take block of code with python statement like class function.
  • it contain single interactive statement.

 flags (optional) and dont_inherit : - if any problem stop to compile the source then it raise flag. default value : -0

 optimize (optional) - optimization level with Default value -1 for compiler.

Example Program for complie() function
Example Program for complie() function

 

Example program for compile() function in python : -

codeInString = 'a = 5\nb=6\nsum=a+b\nprint("sum =",sum)'
codeObejct = compile(codeInString, 'sumstring', 'exec')

exec(codeObejct)

OUTPUT

sum = 11

compile function in python convert the string into a python code object and then execute with exec() method