Ticker

6/recent/ticker-posts

How to Concatenate Matrix in MATLAB?

Question: How to generate the following matrix in MATLAB?

\[ \left[{\begin{array}{cccccccccc} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 3 & 0 & 0 & 0 & 2 & 4 & 6 & 8 & 10 \\ 0 & 0 & 5 & 0 & 0 & 12 & 14 & 16 & 18 & 20 \\ 0 & 0 & 0 & 7 & 0 & 22 & 24 & 26 & 28 & 30 \\ 0 & 0 & 0 & 0 & 11 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 13 & 0 & 0 & 0 & 0 \\ 3 & 3 & 3 & 3 & 0 & 0 & 17 & 0 & 0 & 0 \\ 3 & 2 & 2 & 3 & 0 & 0 & 0 & 19 & 0 & 0 \\ 3 & 2 & 3 & 3 & 0 & 0 & 0 & 0 & 23 & 0 \\ 3 & 3 & 3 & 3 & 0 & 0 & 0 & 0 & 0 & 29 \end{array}}\right] \]

Answer:

  1. The above matrix can easily be generate by first defining a zero matrix \(A\) of \(n \times n\) (in our case it's \(10\)).
  2. Then create arrays of even numbers and store them in \(B\).
  3. Similarly generate \(4 \times 4\) of \(3's\) matrix \(C\)
  4. Replace few elements according to the given condition.
  5. Now, first generate prime numbers on the diagonal
  6. Now substitute (technically concatenate) these smaller size matrices in the bigger matrix \(A\) by specfiying the rows and columns.
Below is the code that follows all the steps mentioned above
clear all; clc; close all;
A = zeros(10);
B2 = 2:2:10;
B3 = B2 + 10;
B4 = B3 +10;
B = [B2;B3;B4];
C = 3*ones(4);
C(2,2:3) = 2;
C(3,2)  = 2;
A = diag(primes(29));
A(2:4,6:10) = B;
A(7:10,1:4) = C;
disp(A)

Output:

     2     0     0     0     0     0     0     0     0     0
     0     3     0     0     0     2     4     6     8    10
     0     0     5     0     0    12    14    16    18    20
     0     0     0     7     0    22    24    26    28    30
     0     0     0     0    11     0     0     0     0     0
     0     0     0     0     0    13     0     0     0     0
     3     3     3     3     0     0    17     0     0     0
     3     2     2     3     0     0     0    19     0     0
     3     2     3     3     0     0     0     0    23     0
     3     3     3     3     0     0     0     0     0    29


Useful MATLAB built-in commands

  • zeros --- Create array of all zeros
  • ones --- Create array of all ones
  • diag --- Create diagonal matrix or get diagonal elements of matrix
  • eye --- Identity matrix
  • cat --- Concatenate arrays
  • horzcat --- Concatenate arrays horizontally
  • vertcat --- Concatenate arrays vertically

Enjoy Learning Simple things, as learning never stops. Thanks for reading!

Post a Comment

0 Comments