Matlab is proprietary tool, and it's license fees are in thousands of dollars. Many open source alternatives exist, which are as good or better than Matlab.

1. Octave: GNU Octave is most popular alternative, and has been in development for more than 30 years. It strives for exact compatibility, so many of your projects developed for MATLAB may run in Octave with no modification necessary. So, if already learned Matlab, you can seamlessly start using Octave. It's front end interface can be chosen to be same as Matlab.

2. Scilab: Best known alternative outside of Octave. It doesn't strive for exact compatibility with Matlab, but is very similar to Matlab

3. Mathematica: It offers features for machine learning, image processing, data mining, etc. It is a superior tool for symbolic mathematics.

4. Python: Python language itself supports a lot of packages which can do all the scientific computing done in Matlab. NumPy is the main package for scientific computing with Python. SymPy is another Python library for symbolic mathematics. It's preferred to use python, as you have to learn python or any other scripting language anyway.

 

 

 

Examples of few common signals in Fourier domain:

When we transform signals from time domain to frequency domain, it's just like any other transformation in maths. A function takes inputs, and transforms it. If there is 1:1 transformation, then we can recover the original input, by applying inverse function to output. However, one thing that stands out in conversion from time domain to frequency domain is that frequency domain bears resemblance to physics. It's easier to visualize sound waves in terms of frequency, so most of the examples about fourier conversion talk about sound waves, but fourier conversion can be applied to any data.

This link shows proof of FT of some common functions: http://www.thefouriertransform.com/pairs/fourier.php

Let's intuitively try some conversion from time domain to freq domain for the below waveforms for all 4 fourier domains: CTFS, CTFT, DTFS, DTFT. Then we'll do rigorous calculation to verify it:

1. Constant signal: This is a signal which is a constant value for all times (-∞ < t < ∞). Since this signal has no variation at all, we don't expect to have any sine/cosine waveforms to reconstruct this dc signal. Infact just the DC offset would be enough to construct this signal. So, in frequency spectrum, we don't expect to see any freq component except f=0 (DC signal).

CTFS: We assume signal to be periodic with arbitrary period T0. We can do this since an infinite long constant signal can be broken into finite duration signals.

Ck = 1/T0 ∫ x(t) e-0kt dt = 1/T0 ∫ 1 * e-0kt dt = 1/T0  [e-0kt ] /(-jω0k) with limits = +T0/2 to -T0/2. For all non zero values of k, Ck = 0. For k=0, we do not integrate (since integration not possible with k in denominator), instead we do C0 = 1/T0 ∫ 1 * dt = 1.

So, only at f=0, we get C0 = 1, all other freq components are 0 as expected.

CTFT: Since for CTFT, signal can be aperiodic, we can compute CTFT of dc signal directly

X(ω) = ∫ x(t) e-jωt dt = ∫ 1 * e-jωt dt = [e-jωt ] /(-jω) with limits of t = +∞ to -∞. However, this doesn't converge to any value, as e-jωt = cos(ωt) - j.sin(ωt) = which oscillates as t->∞. So, we guess that the answer is delta function. If that is true, then x(t) = 1/(2Π) ∫ X(ω) ejωt dω = 1/(2Π) ∫ δ(ω) ejωt dω = 1/(2Π). That implies that X(ω) = (2Π) δ(ω).

Here again, we see that for constant function, freq component exists only at ω=0, with magnitude=2Π

DTFS: If we take discrete samples of constant signal, then we get a signal which is 1 at all samples. Again, treating the signal as periodic with period T0, with N samples in that period, we can compute DTFS.

x[n]=1 for n=0 to N-1. 

Ck = 1/N  ∑ x[n] e-j(2Π/N)kn = 1/N  ∑ 1 * e-j(2Π/N)kn for n=0 to N-1.

Now, we can calc exponential sum formula ∑ ejkn for n=0 to n=N-1. This is same as sum of geometric series = (1 - ejkN) / (1 - ejk) = sin(1/2*N*k)/sin(1/2*k) * ejk(N-1)/2

So, Ck = 1/N  ∑ 1 * e-j(2Π/N)kn = 1/N  * (1 - e-j(2Π/N)kN) / (1 - e-j(2Π/N)k) = 1/N  * (1 - e-j(2Π)k) / (1 - e-j(2Π/N)k)

For k=0, Ck = C0 = 1/N * ∑ 1 * 1 = 1/N * N  =1

For k≠0, Ck = 1/N  * (1 - e-j(2Π)k) / (1 - e-j(2Π/N)k) = 1/N * (1 - 1) / (1 - e-j(2Π/N)k) = 0

Here, just as in CTFS, only at f=0, we get C0 = 1, all other freq components are 0 as expected.

DTFT:  Here, again we have discrete samples, but signal is considered aperiodic. So, we can compute DTFT directly.

x[n]=1 for n=-∞ < n < ∞.

X(e) = ∑ x[n] e-jωn = ∑ 1* e-jωn = with limits of t = +∞ to -∞. However, this doesn't converge to any value, for same reasons as CTFT. So, we guess answer as δ(e)

=> x[n] = 1/(2Π) ∫ X(e) ejωn dω = 1/(2Π) ∫ δ(ω) ejωn dω = 1/(2Π). That implies that X(e) = (2Π) δ(e).

So, as expected, freq component exists only at ω=0, with magnitude=2Π

DFT: DFT is same as DTFS. We can compute DFT by taking N samples of DTFT

DFT Xk or X[k] = samples of X(Ω) at discrete freq =  X(Ω) | ω=2Πk/N where 0 <= k <= N-1.

Since X(e) = (2Π) δ(e) => X0 = (2Π), X1 to XN-1 = 0 as delta function is 0 everywhere else. Result is same as DTFS, except for factor of (2Π) .

2. Impulse signal: It's denoted by δ(t). This is a signal which has a finite value at t=0, but is 0 everywhere else. For analog signals, it's impossible to construct such a signal (since analog signals need to go from 0->1 and then back from 1->0, which will always take a finite amount of time), but mathematically in the limit t->0, we can approximate such a signal. For discrete signal, such a signal is possible to construct by having sample at t=0 as "1", and "0" everywhere else. It's hard to visualize what freq components such a signal would have. But, we do observe that impulse func is an infinitely steep signal in limiting case where t->0. So, it should have infinite freq component in it. It should also have a DC freq component in it, as it's avg value is "1", and not "0". It turns out that such an impulse signal has all freq components from 0 to ∞, of equal magnitude. We can derive this by employing duality property of FT, where taking fourier of frq domain func, gives time domain function back. So, if we have constant signal in time domain, we get impulse func in freq domain, as we saw above. So, constant signal in freq domain will give impulse signal in time domain. That is how we get constant function in freq domain by using duality theorem.

3. train of impulses: It can be rep as periodic impulse func.

4. Sine/Cosine wave: This is a sine/cosine wave with a given freq. It may have a net dc value depending on whether the waveform is shifted up/down from y=0. If it has a net dc value, the only difference in freq spectrun would be that it would have a dc component (f=0) in it's freq spectrum.

A. periodic:

CTFS: It will have only 1 freq component at the freq of sine wave itself. So, Ck will be non zero only at that freq (all others will be 0). This can be seen intuitively as FS is summation of sine/cosine, and this waveform is exactly same as one of the terms, so no other terms of sine/cosine needed to make up this waveform. It also has dc freq component (at f=0) if the square signal has net +ve avg value.

CTFT: We can compute CTFT for any func, periodic or aperiodic. So, we compute CTFT for this signal, and expect to get same result as CTFS. However, as we explained in signal processing page, CTFT is an integral, and hence continuous. So, we'll get impulse function at each of the freq component instead of getting a single discrete line, as we get in CTFS.

B. non periodic: DTFT computed. It will be cont freq spectrum, with freq component similar to DTFS. However, now it's an impulse function centered at ω=+ωk and ω=-ωk.

For x(t)=sin(ω0t) => X(ω) = (2Π)/i * 1/2 * [δ(ω-ω0) - δ(ω+ω0)] => 2 soln are +Π/i and -Π/i at ω=ω0 and ω=-ω0

For x(t)=cos(ω0t) => X(ω) = (2Π) * 1/2 * [δ(ω-ω0) + δ(ω+ω0)] => 2 soln are +Π and +Π at ω=ω0 and ω=-ω0

3. Step signal: This is a step signal, going from 0 to 1 at certain time t.

4. square signal: This signal can have any duty cycle. It's 1 for a while, and 0 elsewhere. It can be thought of as a +ve step signal followed by -ve step signal.

A. periodic: For periodic sqaure wave, we have CTFS, which has freq component at freq=1/T, 3/T, 5/T (i.e odd harmonics). It also has dc freq component (at f=0), if the square signal has net +ve avg value. F

B. non-periodic: For non-periodic square wave, we calc CTFT, which turns out to be a sinc func, where sinc func is defined as sinc(t) = sin(Πt)/(Πt)

5. rectangular signal:

6.

 

Matlab: We can use Matlab software to plot these functions. We use fourier function to calc FT for any function. There is no func for giving FS of periodic func. Instead, we have to solve the series for FS, and have the result plotted. FT is easier to calc using in built "fourier" func, and it can be done for both periodic and aperiodic signals.

Matlab code for plotting the CTFT is:

syms x;
f = exp(-2*x^2); %this is the func whose FT we want. We'll replace this func with our desired func below.
FT = fourier(f); %calculates FT(w) for given f(x). FT is calculated in terms of radians (w)
ezplot(FT,[-1000,+1000]); %plots FT(w) over -1000 rad to +1000rad. By default, it plots from -2Π to +2Π rad

1. Unit Impulse  (aka Dirac delta): use f=dirac(x) => gives o/p=1, i.e a dc plot with value=1 at all x.

2. Sine wave: use f=sin(2*pi*x); => gives o/p as Π(-i)(dirac(w-2Π) - dirac(w+2Π)), since dirac func is infinite at +2Π and -2Π and 0 elsewhere, we just see 0 everywhere

3. Cosine wave: use f=cos(2*pi*x); => gives o/p as Π(dirac(w-2Π) + dirac(w+2Π)), again we just see 0 everywhere

2. Square signal: use f = rectangularPulse(a,b,x). Here a=starting of high pulse, b=end of high pulse. By default, if no a or b provided, i.e rectangularPulse(x), then a=-1/2, b=+1/2

syms x;
f=dirac(x);
FT = fourier(f);
ezplot(FT,[-1000,+1000]);

 

 

Welcome to Maaldaar !!

This site is organized in various sections.

- Education:

- Finance:

- Bank and Credit card Deals

- Shopping deals

- Travel

- Attractions

- Misc info

 

JASPER Gold: JASPER Design Automation bought by Cadence in 2014, and tool now called Jasper Gold (JG):

JG gives more ROI compared to sims, as bugs are caught early and require only 50% manpower.

Jasper provides a wide range of Applications (Apps) covering: Formal Property Verification, Sequential Equivalence Checking, Low-Power Verification, Connectivity Verification, Config/Status Register Verification, X-Propagation Analysis, Structural Property Synthesis, and Behavioral Property Synthesis (just to name a few). Lint and CDC (synchronizers and data coherency issues) too.

formal property verification  (FPV):
-----------------------
it checks if RTL meets certain properties specified. It uses design only, no tb as illegal states specified in assertions are checked for. It helps catch bugs early.
In any line of RTL code, we can right click, and select Activate->visualize line and that will bring up waveform, showing how that RTL target is reached w/o the need for tb.
proofgrid => properties are being proven by running engines.

Sequential Equivalence Checking (SEC):
----------------
Formally prove RTL vs RTL. This is for ECO where we want to formally prove that only intended changes are there.

Low-Power Verification:
----------
automatically creates power aware RTL (UPF/CPF), creates set of checks and evaluates them for all possible i/p combos/ does power aware structural, func and Seq checks
Reduce transitions on clk/mem, does pwr opt, minimizes retention flops

Config/Status Register Verification (CSR):
-------------------
given a reg spec and RTL, automatically derives all properties and runs formal to prove them. IP_XACT i/p as in reg modelling of UVM.
any discrepancy b/w RTL and spec are highlighted with counter examples

X-Propagation Analysis:
--------------
Detect X. verify design init and reset behaviour. Flop reset minimization flow. It can replace GLS.

AFL (automatic Formal Linting):
------------------------------
This consists of
1. Basic Lint checks (HAL = HDL Analysis and Linting) - Naming, coding style, structural, DFT, sim-synth mismatch, etc.
   - Naming and File format checks = RTL_NAMING, RTL_FILEFORMAT
   - Coding style checks - semantics, portability of code = RTL_CODINGSTYLE
   - synthesizability/sim-synth mismatch checks - identifies unsynthesizable constructs, pre-synth/post-synth mismatch = RTL_SYNTH, RTL_SIMSYNTH
   - Structural checks - pesudo synthesize RTL to get structural view, look for feedthru, combinatorial paths = STRUCTURAL
   - FSM checks - compliance to FSM modeling style = FSM
   - Race condition checks - detect all sim race statically possible - read-write, write-write etc = RTL_SIMRACE
   - DFT checks - both in func and test mode that make nodes Uncontrollable and Unobservable = DFT. ADVANCE_DFT
   
2. Advanced Lint checks - (also known as SPS) Structural Property synthesis (SPS):
- automatic checks from RTL such as arithmetic/range overflow, dead code, FSM livelock/deadlock, pragma, bus contention etc. No TB required. These checks do require specifying clock and reset.
   - X assignment = checks whether X assignment are reachable
   - Arithmetic overflow = whetheroverflow can occur in case of arithmetic op
   - Bus contention = whether multiple drivers can drive conflicting values on bus
   - Range overflow = for array access
   - FSM Livelock/deadlock = when design gets stuck in a state.
   - Case = whether certain synthesis pragmas are honored
   - code coverage reachability:
     - Block = If all branches in RTL are reachable
     - FSM = If all branches of FSM are reachable
     - Toggle = If all signals can be toggled
- automated and manual property ranking and classification
- these properties can be fed back into formal or sim env

Behavioral Property synthesis (BPS):
---------------
while SPS is automatically extracted from RTL, BPS is extracted from sim traces (which can be in VCD, FSDB or SHM format), so quality of properties tied to quality and maturity of sims. It's suggested to run periodically thru out the project.
- synthesis of multi cycle, hand shake, implication, black box and white box properties from sim (flow is there w/o sim also).
  - multi cycle = more than 1 or 2 cycle that may never fire in sims
  - automatic properties (assert, assume, cover) as FIFO, counters, FSMs, 1-hot.
    = assert: onehot = $onehot0 ({c0.hit,c1.hit,c2.hit}) => implies one hot
    = assert: FIFO = (q.head == q.tail) |-> q.empty => implies empty state if head eq tail
    = cover: FIFO = !$stable(fifo.rd_ptr) && !$stable(fifo.wr_ptr) => implies tests never change both fifo ptr together
  - user defined properties by specifying interacting signals
- automated and manual property ranking and classification
- properties are classified, and coverage holes are identified via sim. TB is refined and sim rerun to inc func cov. formal cov is also enhanced by analyzing these properties.
- these properties can be fed back into formal or sim env

Formal coverage:
--------
Coverage is of 3 types:
 - Code coverage => checked via imc
 - Func coverage: via cover properties written in TB as SVA/PSL
 - Formal coverage: proof coverage, bound coverage, stimuli coverage

Is my property set complete?

Unreachability:
---------
analyze sim coverage. determine formally unreachable code. No formal expertise reqd, as it just proves reachability/unreachabilty of coverage holes

-------------------------------------
running JG for AFL checks: run irun as usual, just add -jg option.
-------
irun ¡Vjg ¡Vafl ¡Vgui -64 ¡Vjgargs ¡¥-use_license_option¡¦ ¡Vinput <setup>.tcl => this invokes JG with AFL

inputs:
1. custom rule file - selected checks
2. design info file - blackbox, lint pragma
3. custom tcl file - clock, reset, selected checks => This does advanced lint checks
   - syntax: clock <clk_signal> reset <rst_signal>

on the gui, under AFL section on top, we see buttons for these:
1. configure Auto Formal checks
2. extract Auto Formal checks
3. export properties to a task
4. prove exported Auto Formal coverage and checks
5. generate reports: from the extra pull down button at end, click "generate_report -> auto or violation checks". This generates concise report for all viols in html format.

On the bottom of gui, we have violation viewer, waiver list, Auto Formal properties, ..
To create waiver, click on any violation, right click waiver and add waiver for that viol.


--------------------

 

matlab: matlab is proprietary product of Mathworks. 1st version was released in 1984. It's full form is matrix laboratory, as it primarily dealt with matrix computations. MATLAB allows matrix manipulations, plotting of functions and data in 2D/3D, implementation of algorithms, interfacing with programs written in other languages, including C, Python, etc. Although MATLAB is intended primarily for numerical computing, an additional package Simulink, adds graphical multi-domain simulation. We learn matlab since we'll be using it a lot in signal processing, image/video processing, etc.

One of the best places to learn basic Matlab is from here: https://www.tutorialspoint.com/matlab/index.htm

Other useful resource is from matlab user uide or usinh help section of matlab product (click on help->Product_help on top bar after invoking matlab).

Invoking matlab: matlab needs to be installed on your m/c, before you can run it. Usually corporations/universities have licenses of Matlab, so you can use them there. Buying Matlab is expensive, isntead use open source equivalent.I'm presenting Matlab tutorial, since matlab syntax and feel is available in GNU Octave, which is open source equiv of Matlab. So, learning of Matlab can be used in Octave.


matlab -R2016a => starts matlab with version = R2016a. Every year matlab releases 2 versions a and b. Latest release is R2019a.
*.m file are matlab cmd files that can be run from cmdline in matlab. These are scripts that contain all matlab cmds.
ex: matlab_cmd1.m => just type matlab_cmd1 (without .m extension) on prompt of matlab
ex: matlab -nodisplay < cmd1.m => to run cmd1.m without opening gui

After starting matlab, we can start typing cmds on matlab command window. It has >> prompt for entering any cmds.

There is also a "workspace" window on top right, and "Command History" window on bottom right. Workspace window shows all var, while history window shows all cmds entered so far on prompt.

Matlab syntax:

spaces: Matlab is insensitive to spaces. It can parse code correctly even w/o spaces. spaces are not required b/w operators, but added for clarity.

comments: To comment out single line, use %. To comment out multiple lines use:
%{
 .... code ....
%}

format: format cmd changes precision of numbers. i.e format short;

Data types: Matlab is loosely typed, meaning we don't need to define dta type, matlab figures it out automatically.

1. Boolean: true(1) or false (0)

2. Numeric: Integer (signed/unsigned), floating point (single precision and double precision)

3. Text: char/string. string composed of array of char.

variables: A valid variable name starts with a letter, followed by letters, digits, or underscores. MATLAB is case sensitive, so A and a are not the same variable. In Matlab, all vars are arrays, and numeric var are of type double (i.e double precision).

>> a=1; => assigns value of 1 to var "a". If ";" not used at end of cmd, then results are displayed in cmd window (i.e a=1 will be displayed in cmd window). "a" is 1x1 array (array with 1 row and 1 column).  

>>5 => any cmd that returns an o/p val that is not assigned to a var, is assigned to reserved var "ans" (i.e answer). So, in this case, ans is assigned 5.

>> whos a => "whos" on any var shows it's attributes. here it shows "a" as 1x1 array of type "double". It shows 8 bytes are used to store this array "a" (since double precision requires 8 bytes). Just "whos" w/o any var will show info for all var.

>> B = [12, 62, 93, -8, 22; 16, 2, 87, 43, 91; -4, 17, -72, 95, 6] => creates 3x5 array (3 rows x 5 columns). Each row has 5 values. ; indicates end of row. After last row, no ; needed. [ ] indicates it's an array.

To get element from 2nd row, 3rd col of an array, we do B(2,3). NOTE: arrays are defined with square brackets, but accessed via round brackets. Curly brackets {} are 3rd kind of brackets used for creating cell array (explained later).

>> A=magic(5); => creates a 5x5 array with random entries in it.

>> C = [1,2,3] => an array with 1 row and 3 columns. C=[1;2;3] creates an array with 3 rows and 1 column.

>> Mystring = 'hello world'; => strings are char array of 1 row x n cols. single quotes used to store strings. Each char stored in 2 bytes, so this char array of 1x11 stored in 22 bytes.

>> A=ones(5)*4.7, B=magic(5); C=A/B; => multiple cmds can be entered on same line separated by , or ;. Commands that end with a comma display their results, while commands that end with a semicolon do not.

>> s= 1 -1/2 + ...

0.2 => gives result as 0.7. ellipses (...) allow continuation of stmt to next line

cell array: A cell array is a data type with indexed data containers called cells, where each cell can contain any type of data. Cell arrays commonly contain either lists of text, combinations of text and numbers, or numeric arrays of different sizes. Refer to sets of cells by enclosing indices in smooth parentheses (). Access the contents of cells by indexing with curly braces {}

ex: mycell = {'Mary', [3], 'summer', true}. To extract contents of mycell, we use {}. eg. mycell{1} gives Mary, mycell{2} or mycell{1,2} gives 3 and so on. When we use round brackets, we get cell array which is subset of cell array. i.e mycell(1) gives 'Mary' which is a 1x1 array, mycell(2) or mycell(1,2) gives [17] which is again 1x1 array, etc. NOTE: with curly braces, we got extracted values w/o any '..', or [..].

cell(3) => creates a 3x3 cell array of empty matrices.

cell arrays are very useful to store diff kind of data and then to access them in a loop to process them.

operators: 3 types of main operators:

1. Arithmetic operators: to perform numeric computations. +, -, .*(numeric multiplication), ./(numeric right division), .\(numeric left division), .^(numeric power), *(matrix multiplication), /(matrix right division), \(matrix left division), ^(matrix power), etc. Both operands must have same dimension. If one operand is scalar and the other is not, then MATLAB applies the scalar to every element of the other operand—this property is known as scalar expansion. right division (/ or ./) refers to regular division i.e if A=2, B=3, then A/B or A./B = 0.6667. left division (\ or .\) refers to inverted division - A\B or A.\B = B/A = 3/2 =1.5.

2. Relational operators: to compare operands. <, >, ==(equal to), ~=(not equal to), etc. Both operands must have same dimension. operation is applied to each element, and result is for each element, as o(false) or 1 (true). If one operand is scalar and the other is not, then MATLAB applies the scalar against every element of the other operand.

3. logical operators: these can be applied bit-wise, element wise or short circuit. &, |, ~, xor (i.e xor(A,B))

4. Assignment operator: = is an assignment operator as seen above.

5. colon operator (:) => most useful operator of matlab.

>>1:10 => creates a row vector, containing integers from 1 to 10, ans = [1 2 .... 10]

>>x=0:0.2:10 => creates an array with 1 row and 50 columns, with value of x going from 0 to 10 in crements of 0.2, i.e x=[0 0.2 0.4 0.8 .... 50]

: operator within round brackets used to extract specific rows/column entries from arrays. ex:

>> a(:,2) => extracts 2nd col of an array. This col retains it's structure, i.e final result is array with n rows and 1 column

>> a(3,:) => extracts 3rd row of an array. This row retains it's structure, i.e final result is array with 1 row and n columns

>> a(:,2:3) => extracts second and third column of array. final result is array with n rows and 2 columns

>> a(2:3,2:3) => extracts second and third rows and second and third columns. final result is array with 2 rows and 2 columns

Conditional Stmt: All conditional stmt end with keyword "end". 3 kinds:

1. if stmt => optional "elseif" "else" can also be used

ex: if a<30 disp 'small'; else disp 'large'; end => We should write it in multiple lines. If we write all of it in 1 line, we'll need ; to separate out multiple lines of "if"

2. case stmt: switch ..case ... end.

3. for loop => to loop specific num of times

ex: for n=2:6 x(n)=x(n-1); end => repeats with n=2,3,4,5,6

4. while loop => loops as long as condition is true. break (to exit) and continue (to skip to next iteration) stmt can be used from inside while loop.

ex: while fact<100 n=n+1;...; end

functions: can be called by typing name of func with appr args inside round brackets.

>> maxA = max(A,B); here max func is called with args A and B, both of which are arrays. o/p stored in var MaxA. If func returns more than 1 o/p, then we can store them by assigning them to separate var

>> helpFile = which('help');
>> [helpPath,name,ext] = fileparts(helpFile); => here fileparts func returns 3 o/p. We store them in 3 different var. To save memory space, we may want to ignore storing some o/p. We can do that by assigning ~ to that o/p. i.e [~,~,ext] = fileparts(helpFile);

Date functions => "date", "now", "calender", etc func display current date, etc.

import/export functions => to import/export data from external files.

1. importdata func: ex: filename = 'smile.jpg'; A = importdata(filename); image(A); => imports image file and then displays image in window

2. save func: ex: save my_data.out num_array -ascii => my_data.out is the delimited ASCII o/p data file created, num_array is i/p numeric array and −ascii is the specifier.

3. saveas: saveas(gcf,"plot_tmp"); saves graph generated as "plot_tmp".

misc functions:

1. ones, zeros: returns 1 or 0.

ex: y=ones; => returns scalar 1.

ex: y=ones(5); => returns 5x5 matrix with all entries as 1. We could also write it as y=ones(5,5);

ex: y=zeros(2,3) => returns 2x3 array of 0


print/display functions =>


1A. disp(x) => display value of any var (array, string, etc).
ex: A[10 20]; S='Hello'; name='alice', age=12; S=['my name', name,'age',num2str(age)]; => everything in S needs to be string
    disp(A); disp(S); disp('Hello'); => When arg of any function is a text string, we enclose it in single quotes ' ... '. disp 'hello' => is equally valid as we can use cmd syntax instead of func syntax.

1B. sprintf => used to create text. can be stored in a var.
ex: name='alice', age=12; S=sprintf('my name %s age %d', name,age);
    disp(S);

1C. fprintf => used to directly display the text without creating a variable. Always put \n at end. fscanf/fprintf works like C scanf/printf cmds.
ex: fprintf('my name %s age %d \n', name,age); => directly displays this without needing disp

Ploting: Ploting 2D/3D graphs is the most useful feature in Matlab, and used a lot.

1. plot: plot(x,y) plots y against x

ex: x = [-100:5:100]; y = x.^2; plot(x, y) => this plots 2D graph with y=x^2 on y axis and x from -100 to +100 (in increments of 5) on x axis. If increment reduced to 1, then graph becomes smoother as there are more points.

We can add title, labels along the x-axis and y-axis, grid lines and also to adjust the axes to spruce up the graph.

plot(x, y), xlabel('x'), ylabel('x^2'), title('sqaure Graph'), grid on, axis equal, axis ([-20, 20, 0,400]); => this plots x,y graph with label on x axis (as x), y axis (as y^2) and then a title on top of graph. It also adds grid lines on graph. "axis equal" causes equal spacing on both x and y axis (i.e linear plot). axis ([...]) sets min/max values for x,y axis. Here, xmin=-20, xmax=+20, ymin=0, ymax=400.

To plot multiple graphs on same plot, do plot(x1,y1, x2,y2, ...). ex: y = sin(x); g = cos(x); plot(x, y, x, g);

To have separate colors for each graph, add attr in plot(x,y, attr). For color attr, use r=red, g=green, b=blue, w=white, k=black, etc. ex: plot(x, y, 'r', x, g, 'g'); For diif line style, do: plot(x, y1, 'r', x, y2, 'b--o'); => creates lines as --o--o--o--

We can also have legends for graph (using legend cmd). We can print text on graph using text cmd

ex: text(10,-50, 'my custome text'); => prints the given text at x=10,y=-50 on graph. NOTE: x,y are coords in whatever unit is there on axis. If x is in freq(log scale) and y is in db, then x=10Hz,y=-50db is where the text printing starts.

ex: plot(y); => plots data in y verses index of each value. If y is a vector, then the x-axis scale ranges from 1 to length(y). ex:

subplot: With same figure, we can have various plots called subplots. We specify positions of various subplots using subplot cmd. First, specify subplot position for 1st graph, using subplot, then use plot(x,y) to plot 1st graph, then specify position for 2nd graph using subplot, then use plot(x,y) to plot 2nd graph, and so on ...

2. Bar: bar(x,y) plots bar chart for y against x.

3. Contour: A contour line of a function of two variables is a curve along which the function has a constant value. To draw contour map for given func g=f(x,y), first we need to create a meshgrid which defines a set of (x,y) points over domain of func. meshgrid defines x,y range over which we plot function g. Then, we use contour func: contour(x,y,g);

4. surf: Used to create 3D surface plot. Instead of contour, we draw 3D plot of func g=f(x,y). Here again we create meshgrid, then use surf func.

ex: [x,y] = meshgrid(-2:.2:2, -3:0.1:3); g = x .* exp(-x.^2 - y.^2); surf(x, y, g); => Here, func g is plotted on z axis. range of x is from -2 to +2, while y is -3 to +3.

5. ezplot: plot a given func, over range of values specified

ex: ezplot('x^2',[-1,2]) => plots square of x, over range of x=-1 to x=2.

ex: ezplot('x^2 - y^4') => plots x^2-y^4=0 over range x,y=-2Π to +2Π. This is the default range, when range is not specified.

Solving Equations: matlab can solve polynomial eqns using solve func:

ex: solve('(x-3)^2*(x-7)=0') => This solves the cubic eqn, and produces result as ans=[3; 3; 7] = 3x1 array. "=0" iin eqn s optional, as it's understood.

ex: eq = 'y^4 - 7*y^3 + 3*y^2 - 5*y + 9 = 0'; s = solve(eq,'y'); Now s becomes a 4x1 array. Each root can be accessed via s(0), s(1), s(2) and s(3), or as an array s. By default, eqn is solved for x, but to solve for other var, specify that var "y" in solve func.

We can also solve system of eqn.

ex: s = solve('5*x + 9*y = 5','3*x - 6*y = 4'); s.x; s.y; => displays soln for x,y

Calculus: Calc limit, solve differential/integral.

1. limit func: Calculates limit of func. The limit function falls in the realm of symbolic computing. Symbolic computing means using symbols as "x", etc in the o/p instead of getting numerical results. You need to use the syms function to tell MATLAB which symbolic variables you are using. You will get an error, if the function expects symbolic values, and you omit "syms" func for that var.

ex: syms x; limit((x^3 + 5)/(x^4 + 7),2); => 1st arg of limit func is the function, and 2nd arg is what the variable tends to i.e limit x-> a. Here we calc limit for this func, as x approaches 2. If 2nd arg not given, it's assumed to be 0.

2. differential: compute symbolic derivative using func diff().

ex: syms t; f = 3*t^2 + 2*t^(-2); diff(f,2); => this gives derivative as "6 - 12/t^2" (in symbols instead of numerical value). 2nd arg "2" in diff implies 2nd derivative (F''). If 2nd arg not provided, it's assumed to be 1 (1st derivative, F').

We can solve diff eqn symbolically using dsolve. ex: dsolve('D2y - y = 0','y(0) = -1','Dy(0) = 2')

3. integral: inverse of differentiation. "int" cmd calculates indefinite integral of any expression

ex: syms x; int(2*x); => this returns integral as x^2, though in reality integral is x^2+c, where c is arbitrary constant

ex: int(2*x,4,9) => This calculates definite integral with low limit=4, and hi limit=9. Since this yields numerical result, and not in symbols, we don't define x as symbol (i.e syms x; not used here)

Polynomial: To evaluate polynomial at any value, we use polyval func

ex: p = [1 7 0 -5 9]; polyval(p,4); Here p is defined as an array. When used inside polyval func, it represents polynomial P(x)=x^4+7*x^3-5*x+9. It's value is evaluated at x=4, which yields 693.

polyvalm evaluates matrix polynomial.

roots func calculates roots of poly. ex: p = [1 7 0 -5 9]; r = roots(p) => calc 4 roots of the poly eqn, and stores in var "r"

poly func => inverse of roots func, and returns polynomial coefficients

polyfit func => finds coeff of polynomial that fits a set of data in least square sense. We provide numerical values, x and y=f(x), and try to get poly func with max degree "n" that fits y over given values of x.

ex: x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67]; p = polyfit(x,y,4); => here we ask matlab for poly with max degree "4". It returns 5 coeff for x^4, x^3, ...

Transform: Transform functions are ones that maps one domain to other domain. Depending on func used to do transform, it can be quite complex. matlab computes symbolic results.

1. Laplace transform: laplace transform converts f(t) in "t" domain into L{f(t)} in "s" domain. func laplace used for this.

ex: syms s t a w; laplace(a); laplace(t^2); laplace(sin(w*t)) => here we define s, t, a, w as symbols. "s" is for laplace transform o/p var, while others are i/p var going into laplace func. gives results as 1/s^2, 2/s^3 and w/(s^2+w^2)

2. inverse Laplace transform: ilaplace func used. Converts from s domain to t domain.

ex: syms s t ; ilaplace(s/(s^2+4)) => gives cos(2*t) as o/p

3. z transform:

4. Inverse z transform:

5. Fourier transform: converts from time domain to freq domain. freq domain expressed in radians(ω) or hertz(2Πf).

F=fourier(f,u,v); => calculates FT of f(u) as F(v), i.e F(v) = ∫ f(u) e-jvu du. By default, if we omit u,v (i.e F=fourier(f)), then i/p func f is taken as f(x), and o/p func F is given as F(w), i.e F(w) = ∫ f(x) e-jwx dx. Here, w is freq. F=fourier(f,w) imples f(x) and F(w). We have to declare u, v as syms (symbols), else fourier function will give an error as it expects symbols as it's inputs.

Generally, we use function syms fourier(f,t,w) which yields F(w)=  ∫ f(t) e-jwt dt

 ex: syms x; f = exp(-2*x^2); FT = fourier(f); ezplot(FT); => shows FT = (2^(1/2)*pi^(1/2)*exp(-w^2/8))/2, and displays it on graph, with w=-2Π to +2Π.

6. Inverse Fourier transform: converts from freq domain to time domain. ifourier func used

ex: f = ifourier(-2*exp(-abs(w))); => gives result as f = -2/(pi*(x^2 + 1))

7. Fourier series: There is no function for calculating FS of periodic func. Instead, we directly compute terms Ck using integral in matlab and plot them. However, better way is to plot FT. Since FT is a superset of FS, we can look at FT values at distinct freq and get FS from that. Most of the times, FT suffices.

 

 

Generating basic signals: We can generate signals by using built in func. Basic code is:

x=[0:0.005:0.2]; % choose x axis points here
y=func(x); % generate y axis points by applying func to x
plot(x,y); % plot it

1. impulse function: y=dirac(x). Since dirac is a limiting func, whose value is 0 at x≠0, but infinity at x=0 (for continuous function), matlab draws dirac func with missing value at x=0, and 0 everywhere else.

2. sine wave: y=sin(x).

ex: create sine wave of 10Hz freq, T=0.1sec
t=[0:0.005:0.2]; => time is from 0s to 0.2s in steps of 5ms
Amp=1; freq=10; => Amplitude=1, freq=10Hz,
y=Amp*sin(2*pi*freq*t); => plots 2 full waves in 0.2sec, since 10Hz freq => T=0.1sec =10 sine wave/sec
plot(t,y); => plots t on x axis and sine o/p on y axis. plots over range of t from 0 to 0.2sec. plot is little choppy, but can be made smooth by choosing finer steps of 1ms, i.e t=[0:0.001:0.2]

If we choose freq=1000, then sine func argument=2*pi*1000*0.005*n=10*pi*n. So y=0 for all values of n. Then plot(t,y) should be 0 everywhere, since we don't have enough samples to sample any value other than 0. However, what we observe in reality is a choppy plot with y=very small value (10^-13 or so) and it bonces around 0. This is because sin(2*pi)=0 in theory, but computers calculate pi to finite digits only. That results in sin(2*pi) close to 0, but not exactly 0. Whenever you get weird plots like this, always check to make sure you have enough sample points.

ex: create sum of 2 sine waves of 10Hz freq, 

t=[0:0.005:0.2]; => time is from 0s to 0.2s in steps of 5ms
A=1;f1=10;f2=20 => freq=10Hz,20Hz
y=A*sin(2*pi*f1*t) + A*sin(2*pi*f2*t) ; => adds 2 sine waves
plot(t,y) => plots sum of 2 waves, amplitude of final "y" goes from -2 to +2

ex: show gibbs phenomemon in constructing square wave from sine waves (taken from mathworks website)

t = 0:.02:6.28; % t is 1Xn array
y = zeros(10,length(t)); %y is 10Xn array
x = zeros(size(t)); % x is 1Xn array
for k = 1:2:19
   x = x + sin(k*t)/k;
   y((k+1)/2,:) = x;
end
plot(y(1:2:9,:)')

 

------------------


1D. print text on graph
text_to_print = ['SNDR (in db) =',num2str(SNDR1),char(10),'SFDR (in db) =',num2str(SFDR1)]; => char(10) is needed to introduce newline. \n doesn't work.
text(10,-50,text_to_print); => prints the text above on graph.
saveas(gcf,"plot_tmp");

4. matlab native fft function are fft() and inverse is ifft(). To compute fft:
Y = fft(X) => computes the discrete Fourier transform (DFT) of X using a fast Fourier transform (FFT) algorithm. FFT is just bunch of points, it doesn't have any frequency info. We get this frequency info from sampling rate.
Y = fft(X,n) returns the n-point DFT. If no value is specified, Y is the same size as X. If X is a vector and the length of X is less than n, then X is padded with trailing zeros to length n. This is equiv to taking DFT of signal multiplied with a rectangular window. NOTE: for n-point dft, Y is also n point, i.e Y[0] to Y[n-1]. It's periodic with period n, so, only n points reported for Y.

4. PSD of signal
pxx = pwelch(x) => returns PSD of signal x using Welch's overlapped segment averaging estimator. If x is real-valued, pxx is a one-sided PSD estimate. If x is complex-valued, pxx is a two-sided PSD estimate.
[pxx,f] = pwelch(x,window,noverlap,f,fs) returns the two-sided Welch PSD estimates at the frequencies specified in the vector, f.

5. plotspec( ) => This function is defined as below (not std function of matlab). It computes the PSD of a signal, and plots Power in db on Y axis and freq on X axis (log scale).
 
plotspec.m script => uses pwelch signal and then draws plot
------
function [P,F]=PlotSpec(Signal,Fs,Navg,EnFig,color)
 FftLength=round(length(Signal)/Navg);
 Win=window(@blackmanharris,FftLength);

 if FftLength>length(Signal),
  warning('FftLength is greater than the signal length.')
 end

 [Ps,F] = pwelch( sin([0:FftLength-1]'*2*pi/16),Win, floor(3*FftLength/4), FftLength,Fs);
 norm=max(Ps(:,1));
 [P,F] = pwelch( Signal,Win, 0, FftLength,Fs); => note: P is not in db here.
 P=P(:,1)/norm;

if (EnFig==1)
    semilogx(F,10*log10(abs(P)),color,'LineWidth',2);
elseif (EnFig==2)
    plot(F,10*log10(abs(P)),color,'LineWidth',2);
end
    grid on;
    ylabel('Mag (dB)','FontSize',13);
    xlabel('Frequency (Hz)','FontSize',13);

end
-----
ex: [P,F]= PlotSpec(signal, Fs,1,1,'k'); => In John's script
ex: plotspec(signal,Fs,'on',[1 100]); => sampling freq=Fs, freq range on x axis = 1Hz to 100Hz. we can also specify limits separately in other cmd.
ex: [magnitudes, frequencies] = plotspec(signal,Fs,'off'); => instead of plotting, we can also store values in variables


----------------------
Fs1 = 8388608;
digin1 = dlmread('data1.csv'); => reads csv file, put 1 data in each row
figure('Color','w','Name','SDMout-Dec (SV)','WindowStyle','docked');
%PlotSpec(digin1,Fs2,1,1,'k'); => comment starts with %
PlotSpec(digin1,Fs1,1,1,'k');
ylim([-140 0]); => y db limit
xlim([0 Fs1/2]); => x freq limit
------------------------
ex: create sine wave
t=[0:0.005:0.2]; => time is from 0s to 0.2s in steps of 5ms
A=1;f1=10000;f2=50000 => freq=10kHz,50Khz
y=A*sin(2*pi*f1*t) + A*sin(2*pi*f2*t) ; => adds 2 sine waves
plot(t,y) => plots t on x axis and y on y axis

ex: plot fft of sine wave:
f0 = 307;    //sinusoid freq
Fs = 44100; //Sampling frequency in Hz:
Ts = 1/Fs; //Sampling time:
M = 1500; //1500 samples of sinusoid => think of this as the length of a rectangular window that multiplies our infinitely long sinusoid sequence.
n = 0:(M-1); //array of num from 0 to 1499
y = cos(2*pi*f0*Ts*n); //y[n]=cos[2*pi*f*t*n] => draws approx 10 full cosine waveforms = f0/Fs*1500=10. do "plot(n,y);" to see it
Y = fft(y); //computes M point fft since there are M points in y
f = (0:(M-1))*Fs/M; //compute freq points. from 0 to Fs in 1500 steps
plot(f,abs(Y),'*') //plot f on x-axis and mag of Y on y axis, with * as discrete points
xlim([0 Fs/2])
title('Magnitude of DFT')
xlabel('Frequency (Hz)')

-----------------------
ex: save plots in loop
sdm_files = {
         'adc_data_out_ram_raw_k4_b.txt',
         'adc_data_out_ram_raw_k5_b.txt',
         'adc_data_out_ram_raw_k6_b.txt'};

freq=8388608;
%freq=(8384, 789, 123); => makes it an array with integer values accessed thru freq{k}

for k = 1:3
   sdm_file_name = strcat(path, sdm_files{k});
   display(sprintf('Processing %s', sdm_file_name));
   sdm_output = dlmread(sdm_file_name);
   title = sprintf('SDM Ouput k=%d', k+3);
   figure('Color','w','Name', title,'WindowStyle','docked');
   PlotSpec(sdm_output, SDM_freq,1,1,'k');
   ylim([-160 0]);
   xlim([0 SDM_freq/2]);
   out_file_name = strcat(k, '_filt_fbw.jpg');
   saveas(gcf,out_file_name);
end

---------------------------------
end