R Programming #6

  1. Matrix Addition and Subtraction:
  • Given two matrices ( A ) and ( B ), the objective is to perform addition and subtraction between them.
  • Matrix addition and subtraction involve adding or subtracting corresponding elements of the matrices.
  • I used the + operator for addition and the - operator for subtraction in R.
  • The resulting matrices will have the same dimensions as the original matrices.
  • The code creates matrices ( A ) and ( B ), performs addition and subtraction, then prints the results.
  1. Creating a Diagonal Matrix:
  • The task is to create a square matrix with specified values along the diagonal and zeros elsewhere.
  • I usde the diag() function in R to create such matrices.
  • The diag() function takes a vector of values as input and constructs a diagonal matrix using those values.
  • The resulting matrix is printed to verify correctness.
  1. Creating the Diagonal Matrix (Filled with 3s):
  • I started by creating a 5×5 matrix with 3s along the main diagonal (from top-left to bottom-right).
  • Filling the Upper Triangle (with 1s):
    • I identified and filled the upper triangle of the matrix with 1s.
    • The upper triangle includes all elements above the main diagonal.
    • Filling the Lower Triangle (with 2s):
      • Similarly, I identified and filled the lower triangle of the matrix with 2s.
      • The lower triangle includes all elements below the main diagonal.
      • After filling the upper and lower triangles, I obtained the desired matrix pattern.

      GitHub Repository:

      https://github.com/mramalho4/rprog-repo.git

      Leave a comment