---
# System prepended metadata

title: Midterm Syntax Key Note

---

# Midterm Syntax Key Note

## Getting Help (`help`)

Use the **`help` command** to see the syntax and description for any MATLAB function directly in the Command Window. This is useful for checking how to use a function or avoiding naming conflicts with your own variables.

*(Code cell with `help plot`)*


```matlab
help plot
```

     plot - 2-D line plot
        This MATLAB function creates a 2-D line plot of the data in Y versus the
        corresponding values in X.
    
        Vector and Matrix Data
          plot(X,Y)
          plot(X,Y,LineSpec)
          plot(X1,Y1,...,Xn,Yn)
          plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn)
          plot(Y)
          plot(Y,LineSpec)
    
        Table Data
          plot(tbl,xvar,yvar)
          plot(tbl,yvar)
    
        Additional Options
          plot(ax,___)
          plot(___,Name,Value)
          p = plot(___)
    
        Input Arguments
          X - x-coordinates
            scalar | vector | matrix
          Y - y-coordinates
            scalar | vector | matrix
          LineSpec - Line style, marker, and color
            string scalar | character vector
          tbl - Source table
            table | timetable
          xvar - Table variables containing x-coordinates
            string array | character vector | cell array | pattern |
            numeric scalar or vector | logical vector | vartype()
          yvar - Table variables containing y-coordinates
            string array | character vector | cell array | pattern |
            numeric scalar or vector | logical vector | vartype()
          ax - Target axes
            Axes object | PolarAxes object | GeographicAxes object
    
        Name-Value Arguments
          Color - Line color
            RGB triplet | hexadecimal color code | "r" | "g" | "b" | ...
          LineStyle - Line style
            "-" (default) | "--" | ":" | "-." | "none"
          LineWidth - Line width
            0.5 (default) | positive value
          Marker - Marker symbol
            "none" (default) | "o" | "+" | "*" | "." | ...
          MarkerIndices - Indices of data points at which to display markers
            1:length(YData) (default) | vector of positive integers |
            scalar positive integer
          MarkerEdgeColor - Marker outline color
            "auto" (default) | RGB triplet | hexadecimal color code | "r" |
            "g" | "b" | ...
          MarkerFaceColor - Marker fill color
            "none" (default) | "auto" | RGB triplet | hexadecimal color code |
            "r" | "g" | "b" | ...
          MarkerSize - Marker size
            6 (default) | positive value
          DatetimeTickFormat - Format for datetime tick labels
            character vector | string
          DurationTickFormat - Format for duration tick labels
            character vector | string
    
        Examples
          openExample('graphics/CreateLinePlotExample')
          openExample('graphics/PlotMultipleLinesExample')
          openExample('graphics/CreateLinePlotFromMatrixExample')
          openExample('graphics/SpecifyLineStyleExample')
          openExample('graphics/SpecifyLineStyleColorAndMarkerExample')
          openExample('graphics/DisplayMarkersAtSpecificDataPointsExample')
          openExample('graphics/SpecifyLineWidthMarkerSizeAndMarkerColorExample')
          openExample('graphics/AddTitleAndAxisLabelsExample')
          openExample('matlab/SpecifyDurationTickFormatsExample')
          openExample('graphics/PlotTableDataExample')
          openExample('graphics/PlotTableMutliVariablesExample')
          openExample('graphics/PlotSpecifyAxes19bExample')
          openExample('graphics2/ChangeLinePropertiesUsingHandlesExample')
          openExample('graphics/PlotCircleExample')
    
        See also title, xlabel, ylabel, xlim, ylim, legend, hold, gca, yyaxis,
          plot3, loglog, Line Properties
    
        Introduced in MATLAB before R2006a
        Documentation for plot
           doc plot
    
        Other uses of plot
    
           alphaShape/plot    matlab.buildtool.Plan/plot    tall/plot
           digraph/plot       polyshape/plot                timeseries/plot
           graph/plot
    


## File I/O

### save to .mat
> for saving variable

Saves specified workspace variables to a binary .mat file


```matlab
var1 = 1:10;
var2 = 'test';
save('my_data.mat', 'var1', 'var2') 
```

### load file


```matlab
load('my_data.mat') 
```

### save figure


```matlab
plot(1:10)
saveas(gcf, 'my_plot.fig') 
```




    
![output_9_0](https://hackmd.io/_uploads/S1iQow0Cle.png)

    



## Matrix or Array

### Creating Vectors/Arrays

Common methods for creating vectors:


```matlab
% Creates a vector from 1 to 10 with a step of 2 [cite: 475]
vec = 1:2:10

% Creates 5 points evenly spaced between 0 and 10 [cite: 477, 478]
x = linspace(0, 10, 5)

% Creates 8 points between 10^1 and 10^4 [cite: 486, 488]
y = logspace(1, 4, 8)
```




<html><body><pre>vec = 1×5 double
     1     3     5     7     9
</pre></body></html>






<html><body><pre>x = 1×5 double
         0    2.5000    5.0000    7.5000   10.0000
</pre></body></html>






<html><body><pre>y = 1×8 double
1.0e+04 *

    0.0010    0.0027    0.0072    0.0193    0.0518    0.1389    0.3728    1.0000
</pre></body></html>



### Element-wise Operations (. Operator)

computation for the element of the matrix

se the dot (.) before *, /, \ , ^ to perform operations element by element. Arrays must generally be the same size or one must be a scalar.


```matlab
A = [1 2];
B = [3 4];

% Element-wise multiplication (1*3, 2*4)
C_mult = A .* B % [cite: 635, 649]

% Element-wise division (1/3, 2/4)
C_div = A ./ B % [cite: 649]

% Element-wise power (1^2, 2^2)
C_pow = A .^ 2 % [cite: 649]
```




<html><body><pre>C_mult = 1×2 double
     3     8
</pre></body></html>






<html><body><pre>C_div = 1×2 double
    0.3333    0.5000
</pre></body></html>






<html><body><pre>C_pow = 1×2 double
     1     4
</pre></body></html>





### Matrix Operations (Linear Algebra)

computation for linear algebra opertation

Standard linear algebra operations. Note the specific use of backslash (\) for solving linear systems.


```matlab
A = [1 2; 3 4];
B = [5; 6];

% Standard matrix multiplication
C = A * B % [cite: 642, 649]

% Matrix left division. This is the best way to solve
% the linear equation A*x = B for x [cite: 652-657]
x = A \ B % [cite: 649, 657]
```




<html><body><pre>C = 2×1 double
    17
    39
</pre></body></html>






<html><body><pre>x = 2×1 double
   -4.0000
    4.5000
</pre></body></html>




## Display or print

aka 吐出答案

* Simply typing a variable name or calculation shows the result assigned to `ans`.
* **`disp(variable)`**: Displays the *value* of the variable without printing its name. It works well for numbers and text strings.
* **`fprintf('format string', variables...)`**: Provides the most control for printing formatted text and numbers, using conversion characters (like `%f` for float, `%d` for integer, `%s` for string) and escape characters (like `\n` for new line). Use `num2str()` or `int2str()` to convert numbers to strings if needed for `disp`.


```matlab
disp(100/81)
fprintf('100 divided by 81: %6.2f', 100/81)
```

        1.2346
    
    100 divided by 81:   1.23

## Logical Structure

### `if`, `else`, `elseif`


```matlab
grade = 85;

if grade >= 90
    disp('A') 
elseif grade >= 80
    disp('B') 
else
    disp('C or below') 
end
```

    B


### `switch`


```matlab
day = 3;
switch day
    case {1, 7} % Group multiple cases with { } 
        disp('Weekend')
    case 2
        disp('Monday')
    otherwise % Optional: runs if no case matches aka default
        disp('Other weekday')
end
```

    Other weekday


### `try`, `catch`


```matlab
try 
    % Attempt a risky operation
    result = 1 / 0;
catch 
    % This block runs if an error occurs in 'try' [cite: 1114]
    disp('Error: Division by zero.')
end
```

### `while`, `for`


```matlab
n = 1;
while n <= 5 
    disp(n)
    n = n + 1;
end

total = 0;
for ii = 1:10 
    total = total + ii;
end
disp(total)

% Loop over a specific array
for val = [5 9 7] 
    disp(val)
end

% A 'for' loop iterates over the *columns* of a matrix
for col = [1 2 3; 4 5 6] 
    disp('Column is:')
    disp(col) % Displays [1;4], then [2;5], then [3;6] [cite: 100-106]
end
```

         1
    
         2
    
         3
    
         4
    
         5
    
        55
    
         5
    
         9
    
         7
    
    Column is:
         1
         4
    
    Column is:
         2
         5
    
    Column is:
         3
         6
    


## user defined function

Creating your own functions in separate .m files. The filename must match the function name.


```matlab
% --- Save this content as 'dist.m' ---
function [d, x_diff] = dist(p1, p2) 
% H1 Line: Calculates the distance between two points. [cite: 292, 298]
    %
    % Help Text: This function finds the Euclidean distance
    % between p1 (x1, y1) and p2 (x2, y2). [cite: 300]
    
    % Use 'nargin' to check number of inputs [cite: 313]
    if nargin < 2 
        p2 = [0, 0]; % Set default for p2 if not provided [cite: 321]
    end
    
    x_diff = p1(1) - p2(1);
    y_diff = p1(2) - p2(2);
    d = sqrt(x_diff^2 + y_diff^2);

    % All output arguments (d, x_diff) must be assigned a value [cite: 289]
end 
```

## 2D plot

### single plot


```matlab
x = 0:0.1:2*pi; 
y = sin(x); 
plot(x, y) 

% Add annotations 
title('Plot of sin(x)') 
xlabel('x') 
ylabel('sin(x)') 
grid on 
xlim([0 2*pi]) % Set x-axis limits [cite: 784, 785]
```




    
![output_35_0](https://hackmd.io/_uploads/rk7SsPAAle.png)

    



### multiplot


```matlab
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);

% Plot both at once with 'LineSpec' strings ('red dashed', 'blue dotted-o')
plot(x, y1, 'r--', x, y2, 'b:o') 

% Add a legend 
legend('sin(x)', 'cos(x)', 'Location', 'southwest') 
```




    
![output_37_0](https://hackmd.io/_uploads/ByjSjvARxe.png)

    



### Logarithmic Plots


```matlab
t = 0:10000;
N = exp(-t/5730); % Radioactive decay example [cite: 338]

figure(1) % Create a new figure window [cite: 443, 445]

% Use 'subplot' to create a grid of plots (m, n, p) [cite: 450-452]
subplot(2, 2, 1) 
plot(t, N); title('plot') % [cite: 332]

subplot(2, 2, 2)
semilogx(t, N); title('semilogx') % [cite: 333]

subplot(2, 2, 3)
semilogy(t, N); title('semilogy') % [cite: 334]

subplot(2, 2, 4)
loglog(t, N); title('loglog') % [cite: 335]
```




    
![output_39_0](https://hackmd.io/_uploads/BJMIjvCCge.png)

    



### dual y axis


```matlab
x = 0:0.1:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);

figure(3)

% Activate the LEFT axis [cite: 516]
yyaxis left 
plot(x, y1)
ylabel('Left-side Data')

% Activate the RIGHT axis [cite: 517]
yyaxis right 
plot(x, y2)
ylabel('Right-side Data')
```




    
![output_41_0](https://hackmd.io/_uploads/BkqUiPC0ll.png)

    






    
![output_41_1](https://hackmd.io/_uploads/rJgvsDRRgx.png)

    






    
![image](https://hackmd.io/_uploads/rkL2aDAAeg.png)



### Text Formatting in Plots

Use TeX-like commands within strings for titles, labels, legends, and `text()` objects to add formatting and symbols :
* `\bf` (bold), `\it` (italic). Use `{}` to limit scope (e.g., `{\it only this}`).
* `_` for subscript, `^` for superscript (use `{}` for multiple characters, e.g., `x_{12}`).
* Greek letters (e.g., `\alpha`, `\theta`).
* For complex math, use `'Interpreter', 'latex'` .


## Lab0

```matlab=
% Classwork of Week 3: MATLAB script file to input three temperatures in
% degree Celcius, convert them to Kelvin and Fahrenheit, record the time
% at which the input was captured, and save all the input and output data
% to Temp.mat

% Clearing all variables in the workspace
clear; 

% Clear the screen on the workspace
clc; 

% Prompt the user to input 3 temperatures in the required format
TempC = input('Please input three temperatures in Celcius in the format [T1 T2 T3]: ');

% Capture the timing information at this instant
TimeIn = clock;

% Do conversion from Celcius to Kelvin
TempK = TempC + 273.15;

% Do conversion from Celcius to Fahrenheit
TempF = 9/5*TempC + 32;

% Save all variables in workspace to Temp.mat
save('Temp.mat')
```

## Lab1

```matlab
% Classwork of Week 6: MATLAB script file to compute and plot the 
% relativistic and approximate classical energy formula as a function of 
% the normalized speed

% Clearing the workspace, the screen, and the content of any current figure
clear; clc; clf; 

% Speed normalized w.r.t. to the speed of light
alpha = linspace(0,1,50);

% Declare the energy arrry
Ek = zeros(length(alpha),2);

% The first column stores the relativistic energy value
Ek(:,1) = sqrt(1+alpha.^2./(1-alpha.^2))-1;

% The second column stores its classical approximation
Ek(:,2) = 1/2*alpha.^2;

% Plot both as a function of alpha with a thickened linewidth
plot(alpha,Ek,'LineWidth',1)

% Turn on grid lines
grid on

% Include the title of the plot
title('Normalized kinetic energy as a function of \alpha','FontSize',14);

% Include the x-label and y-label
xlabel('\alpha','FontSize',14);
ylabel('$\frac{E_K}{mc^2}$','Interpreter','latex','FontSize',14);

% Include the best-positioned legend
legend('Relativistic','Newtonian',Location='best')

% Print the figure to a 300dpi pdf file
print('Ek','-dpdf','-r300');

```

![image](https://hackmd.io/_uploads/ry0NpDAAgl.png)


## Lab2

```matlab
% Classwork of Week 7: MATLAB script file to compute the photon energy for
% visible light and the corresponding characteristic temperature

% Clearing the workspace, the screen, and the content of any current figure
clear; clc; clf; 

% Definition of various physical constants
h = 6.62607015e-34;
c = 299792458;
q = 1.60217663e-19;

% There's a typo in the slide, the correct value of the Boltzmann constant
% should have been kB = 1.380649e-23;
kB = 1.308649e-23;

% Specification of the data points for the wavelength lambda; 
% there's another typo here: the correct range of visible wavelengths 
% should be 400 to 700 nm
lambda = linspace(400e-9,900e-9,100);

% Computation of the photon energy
E = h*c./lambda;

% Computation of the characteristic temperature
T = E/kB;

% Since this is the first plot, it's optional to include the following
% command
% yyaxis left;

% Plot the rescaled energy vs the rescaled wavelength
plot(lambda/1e-9, E/q,'b-');

% Include the y-label on the right-hand-side 
ylabel('\bfEnergy (eV)','FontSize',11);

hold on;

% Tells MATLAB that we next make plot based on the y-axis on the right
yyaxis right;

% Plot the rescaled energy vs the rescaled temperature
plot(lambda/1e-9, T/1e3,'r-');

% Include the y-label on the left-hand-side 
ylabel('\bfTemperature (10^3 K)','FontSize',11)

% Turn on grid lines
grid on

% Include figure legends at the best location
legend('Energy','Temperature','Location','best','FontSize',11)

% Specify the x-label
xlabel('\lambda (nm)','FontSize',11)

```

![image](https://hackmd.io/_uploads/HJKmTDACxx.png)


# NIST PQC Standards (FIPS 203 & 204)

### Section 1: Why We Must Change

1.1. **Current Foundation:**

- **Key Exchange:** ECDH
- **Signatures:** RSA, ECDSA

1.2. **The Vulnerability:**

- Factoring and **Discrete Logarithms**

1.3. **The Threat:**

- **Shor's Algorithm** breaks current cryptography
- "Harvest Now, Decrypt Later"

1.4. **NIST PQC Competition**

---

### Section 2: Lattice Cryptography

2.1. **Hard Problems:**

- **SIS** (Shortest Integer Solution)
- **LWE** (Learning with Errors)

2.2. **Practical Implementation:**

- **MLWE** (Module Learning with Errors)
- **Ring $R_q$**: Structured, compact, fast
- **NTT**: Fast polynomial multiplication

2.3. **Tools:**

- **SHAKE** (XOF)
- **RBG** (SP 800-90)

---

### Section 3: FIPS 203 (ML-KEM)

3.1. **Overview:**

- **KEM:** `KeyGen`, `Encaps`, `Decaps`
- **IND-CCA2 Security**

3.2. **K-PKE Core:**

- `K-PKE.Encrypt`: Uses public key and noise
- `K-PKE.Decrypt`: Uses secret to recover message

3.3. **Requirements:**

- K-PKE alone is not secure
- Parameter sets: ML-KEM-512, 768, 1024

---

### Section 4: FIPS 204 (ML-DSA)

4.1. **Overview:**

- **DSA:** `KeyGen`, `Sign`, `Verify`
- Fiat-Shamir with Aborts

4.2. **Algorithms:**

- `ML-DSA.KeyGen`: Generates keys
- `ML-DSA.Sign`: Rejection sampling prevents key leakage
- `ML-DSA.Verify`: Uses **Hint ($h$)**

4.3. **Variants:**

- **Pure ML-DSA**
- **Hedged Signing:** Best practice
- **Pre-Hash (HashML-DSA):** For large files

---

### Section 5: Summary & Action

5.1. **Summary:**

- Shor's Algorithm breaks RSA/ECC
- Lattices (MLWE) are quantum-resistant
- **FIPS 203:** Key exchange
- **FIPS 204:** Signatures

5.2. **Q&A**