Skip to content
IT-406 · Introduction to MATLAB/SciLab/Web Design/Quick Revision Short Notes

Introduction to MATLAB/SciLab/Web Design (IT-406) - Unit 4 Short Notes

UNIT 4: Intermediate Programming & Interactive Web Integration

A. Advanced MATLAB / SciLab Programming & Analysis

1. Scripting vs. Functions

  • Script File (.m): Sequence of commands executed in the base workspace. Variables created here are accessible after script runs.

  • Function File (.m): Defines a reusable module with its own local workspace. Variables inside are not accessible outside unless returned as outputs.

  • Syntax: function [outputArg1, outputArg2] = functionName(inputArg1, inputArg2)

    • Output arguments are optional. Function name must match file name.
  • Variable Scope:

    • Local: Default inside functions. Exists only during function execution.

    • Global: Declared with global varName. Shared across multiple functions and base workspace (use sparingly).

  • [!TIP] Exam Focus: Difference in workspace is a very common question. A function cannot directly modify variables in the caller's workspace unless they are outputs or global.

2. Control Flow & Logic

  • if-elseif-else: Used for range-based or complex conditions.

    
    if condition1
    
        % code
    
    elseif condition2
    
        % code
    
    else
    
        % code
    
    end
    
    
  • switch-case: Efficient for testing a single variable against multiple discrete values.

    
    switch expression
    
        case value1
    
            % code
    
        case {value2, value3} % Multiple cases
    
            % code
    
        otherwise
    
            % code
    
    end
    
    
  • Nesting: if/switch statements and loops (for, while) can be nested to any depth for complex logic.

3. Data Structures

  • Cell Arrays (cell): Store heterogeneous data (different types/sizes). Accessed using curly braces {}.

    • Creation: C = {1, 'text', [1 2 3]};

    • Access content: C{2} returns 'text'.

    • Access cell: C(2) returns a cell containing 'text'.

  • Structures (struct): Store named fields (like a database record). Fields can hold any data type.

    • Creation: s.name = 'John'; s.age = 30; s.scores = [85 90];

    • Access: s.name or s('name').

  • Tables (table): (MATLAB) Store column-oriented, mixed-type data. Ideal for spreadsheet-like data. Columns have names and can be accessed by name or index.

    • T = table(var1, var2, 'VariableNames', {'Col1','Col2'});

    • Access column: T.Col1 or T{:,1}.

4. File I/O (Input/Output)

  • Low-Level I/O (Full Control):

    1. fid = fopen('filename.txt', 'r'); % 'r' read, 'w' write, 'a' append. Check fid == -1 for error.

    2. A = fscanf(fid, '%d %f', [2 Inf]); % Read formatted data (2 rows, unknown columns).

    3. fprintf(fid, 'Value: %6.2f\n', x); % Write formatted text.

    4. fclose(fid); Always close the file.

  • High-Level I/O (Simpler):

    • Import: data = readmatrix('data.csv'); T = readtable('data.txt');

    • Export: writetable(T, 'output.csv');

    • MAT-files: save('mydata.mat', 'var1', 'var2'); load('mydata.mat'); (Saves/loads entire variables quickly).

5. Debugging and Profiling

  • Debugging Tools:

    • Set breakpoints (click left margin) to pause execution.

    • Use Step (F10), Step In (F11), Step Out to navigate.

    • View workspace and command window for variable values at breakpoint.

  • Common Errors: Undefined function or variable, Index exceeds matrix dimensions, Missing endor)`.

  • Profiling: profile on; myFunction(); profile viewer; Shows which functions took most time and how many times they were called.


B. Advanced Visualization & GUI Basics (MATLAB/SciLab)

1. Advanced Plot Customization

  • Axes & Figure: xlabel('X'), ylabel('Y'), title('Plot'), grid on, axis([xmin xmax ymin ymax]).

  • Line Properties: Specify during plot: plot(x, y, 'r--o', 'LineWidth', 2, 'MarkerSize', 8);

    • 'r--o' = red dashed line with circle markers.
  • Legends: legend('Data1', 'Data2', 'Location', 'best');

  • Subplots: subplot(m,n,p); Divides figure into m x n grid, makes plot p active.

  • 3D Plotting:

    • plot3(x,y,z) : 3D line.

    • [X,Y] = meshgrid(x,y); Z = X.^2 + Y.^2;

    • mesh(X,Y,Z) : Wireframe surface.

    • surf(X,Y,Z) : Filled surface.

    • contour3(X,Y,Z) : 3D contour lines.

2. Introduction to Graphical User Interfaces (GUIs)

  • Components: Axes (for plots), push buttons, sliders, edit text boxes, static text labels.

  • Creation Methods:

    • GUIDE (MATLAB): Drag-and-drop layout builder (being phased out but still used).

    • Programmatic: Create components using uicontrol function.

  • Callbacks: Each UI component has an associated callback function (e.g., pushbutton1_Callback). This function executes when the user interacts (clicks, drags).

  • Simple Interactive Example:

    1. GUI has a slider and an axes.

    2. Slider callback reads slider value: freq = get(hObject, 'Value');

    3. Callback updates plot on axes: plot(axesHandle, x, sin(freq*x));


C. Intermediate Web Design & Interactivity

1. Introduction to JavaScript

  • Role: Client-side scripting for dynamic, interactive web pages.

  • Inclusion:

    • Inline: <script> ... </script>

    • External (best practice): <script src="script.js"></script>

  • Basics: Variables (let, const, var), data types, operators, console.log() for debugging.

  • Functions:

    
    function functionName(param1, param2) {
    
        // code
    
        return result; // optional
    
    }
    
    
  • Events: Assign handler to HTML element attribute or via JS.

    
    <button onclick="myFunction()">Click</button>
    
    <button id="myBtn">Click</button>
    
    <script>document.getElementById('myBtn').onclick = myFunction;</script>
    
    

2. DOM Manipulation with JavaScript

  • DOM Concept: Tree of nodes (elements, text, attributes) representing the HTML document.

  • Selecting Elements:

    • document.getElementById('id') → Single element.

    • document.getElementsByClassName('class') → Live HTMLCollection.

    • document.querySelector('cssselector') → First match.

    • document.querySelectorAll('cssselector') → NodeList of all matches.

  • Modifying Content:

    • element.innerHTML = '<b>New</b>'; (Parses HTML tags).

    • element.textContent = 'New'; (Plain text, safer).

  • Modifying Styles: element.style.property = 'value'; (e.g., element.style.color = 'red';).

  • Creating/Removing:

    
    let newDiv = document.createElement('div');
    
    newDiv.textContent = 'Hello';
    
    document.body.appendChild(newDiv);
    
    document.getElementById('old').remove();
    
    

3. Form Handling & Validation

  • Accessing Values: let val = document.getElementById('username').value;

  • Validation Example (in submit handler):

    
    document.getElementById('myForm').onsubmit = function(event) {
    
        let email = document.getElementById('email').value;
    
        if (!email.includes('@')) {
    
            alert('Invalid email');
    
            event.preventDefault(); // Stop form submission
    
        }
    
    };
    
    
  • event.preventDefault(): Crucial to handle form with JS instead of sending to server.

4. Introduction to Dynamic Content & APIs

  • API (Application Programming Interface): Set of rules allowing software to communicate. Web APIs return data (often JSON).

  • Fetch API (Modern):

    
    fetch('https://api.example.com/data')
    
        .then(response => response.json()) // Parse JSON
    
        .then(data => console.log(data))
    
        .catch(error => console.error('Error:', error));
    
    
  • JSON (JavaScript Object Notation): Lightweight data format: {"name": "John", "age": 30}. Parse with JSON.parse(jsonString). Stringify with JSON.stringify(object).


D. Integration Concepts & Project Workflow

1. Connecting MATLAB/SciLab Output to the Web

  • Export Plot as Image:

    
    plot(x, y);
    
    saveas(gcf, 'myplot.png'); % Saves current figure
    
    % or
    
    exportgraphics(gcf, 'myplot.jpg', 'Resolution', 300);
    
    
  • Embed in HTML: <img src="myplot.png" alt="My Plot">

  • Workflow: Use MATLAB/SciLab for heavy computation/plot generation → save as image/data file → HTML/JS displays the result.

2. Basic Project Structure


project_folder/

│   index.html

│   style.css

│   script.js

│
├── data/

│   └── results.csv

│
└── images/

    └── plot.png

  • Relative Paths: From index.html, link CSS: href="style.css". Link image: src="images/plot.png". Never use absolute paths like C:\Users... for web projects.

3. Version Control Introduction (Git)

  • Purpose: Track changes, revert to previous states, collaborate.

  • Basic Commands:

    • git init : Initialize repository in current folder.

    • git add filename : Stage file for commit.

    • git commit -m "Message" : Save staged changes locally.

    • git status : Show changed/untracked files.

  • Remote (GitHub/GitLab):

    • git remote add origin <repository_url>

    • git push -u origin main : Upload commits to remote.

    • git pull origin main : Download and merge remote changes.

Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in