Question: How to generate the following matrix in MATLAB?
Answer:
- The above matrix can easily be generate by first defining a zero matrix
of (in our case it's ). - Then create arrays of even numbers and store them in
. - Similarly generate
of matrix - Replace few elements according to the given condition.
- Now, first generate prime numbers on the diagonal
- Now substitute (technically concatenate) these smaller size matrices in the bigger matrix
by specfiying the rows and columns.
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!
0 Comments