Creating, Concatenating, and Expanding Matrices - MATLAB & Simulink

In MATLAB and Simulink, working with matrices is a fundamental task. Here's a guide on creating, concatenating, and expanding matrices:

Creating Matrices

  1. Directly Creating Matrices:

    • You can create matrices directly by specifying the elements in square brackets [].

    matlab
    % Create a 2x3 matrix
    A = [1, 2, 3; 4, 5, 6];
    
  2. Using Functions:

    • Use functions like zeros, ones, eye, and rand to create matrices with specific properties.

    matlab
    % Create a 3x3 matrix of zeros
    Z = zeros(3);
    
    % Create a 3x3 matrix of ones
    O = ones(3);
    
    % Create a 3x3 identity matrix
    I = eye(3);
    
    % Create a 3x3 matrix with random elements
    R = rand(3);
    

Concatenating Matrices

  1. Horizontal Concatenation:

    • Concatenate matrices side-by-side using square brackets [].

    matlab
    A = [1, 2, 3];
    B = [4, 5, 6];
    C = [A, B]; % Result: [1, 2, 3, 4, 5, 6]
    
  2. Vertical Concatenation:

    • Concatenate matrices top-to-bottom using semicolons ;.

    matlab
    A = [1, 2, 3];
    B = [4, 5, 6];
    C = [A; B]; % Result: [1, 2, 3; 4, 5, 6]
    

Expanding Matrices

  1. Expanding by Assignment:

    • Expand a matrix by directly assigning values to elements outside the current size.

    matlab
    A = [1, 2, 3];
    A(2, 4) = 10; % Expands A to 2x4: [1, 2, 3, 0; 0, 0, 0, 10]
    
  2. Using Functions:

    • Use the padarray function from the Image Processing Toolbox to pad matrices.

    matlab
    A = [1, 2, 3];
    B = padarray(A, [1, 1], 0, 'post'); % Pads with zeros at the end
    

Example of Creating, Concatenating, and Expanding Matrices

matlab
% Create matrices
A = [1, 2; 3, 4];
B = [5, 6; 7, 8];

% Horizontal concatenation
C_hor = [A, B]; % Result: [1, 2, 5, 6; 3, 4, 7, 8]

% Vertical concatenation
C_ver = [A; B]; % Result: [1, 2; 3, 4; 5, 6; 7, 8]

% Expanding matrices
A(3, 3) = 9; % Expands A to 3x3: [1, 2, 0; 3, 4, 0; 0, 0, 9]

% Display results
disp('Horizontal Concatenation:');
disp(C_hor);
disp('Vertical Concatenation:');
disp(C_ver);
disp('Expanded Matrix:');
disp(A);

These techniques will help you efficiently create, concatenate, and expand matrices in MATLAB and Simulink