Concept Flow - Matrix arithmetic
Create Matrix A
Create Matrix B
Choose Operation
Add
Result Matrix
Start by creating two matrices, then pick an arithmetic operation (add, subtract, multiply) to get the result matrix.
A <- matrix(c(1,2,3,4), nrow=2) B <- matrix(c(5,6,7,8), nrow=2) C <- A + B C
| Step | Action | Matrix A | Matrix B | Operation | Result C |
|---|---|---|---|---|---|
| 1 | Create A | [1 3; 2 4] | - | - | - |
| 2 | Create B | - | [5 7; 6 8] | - | - |
| 3 | Add A + B | [1 3; 2 4] | [5 7; 6 8] | Addition | [6 10; 8 12] |
| 4 | Output C | - | - | - | [6 10; 8 12] |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| A | NULL | [1 3; 2 4] | [1 3; 2 4] | [1 3; 2 4] | [1 3; 2 4] |
| B | NULL | NULL | [5 7; 6 8] | [5 7; 6 8] | [5 7; 6 8] |
| C | NULL | NULL | NULL | [6 10; 8 12] | [6 10; 8 12] |
Matrix arithmetic in R: - Create matrices with matrix(c(...), nrow=...) - Addition/Subtraction: element-wise, matrices must be same size - Multiplication: use %*% for matrix multiplication - Result is a new matrix - Dimensions must match rules for each operation
%*% do when applied between two matrices?+ and - perform element-wise addition and subtraction respectively, while %*% is used for matrix multiplication.%*%%*% multiplies matrices according to linear algebra rules, not element-wise.%*% = matrix multiplication [OK]matrix() takes a vector of values and parameters nrow and ncol to specify dimensions.c(1, 2, 3, 4) and named arguments nrow=2, ncol=2. matrix(1, 2, 3, 4, nrow=2, ncol=2) has wrong argument format. matrix(c(1, 2, 3, 4), rows=2, cols=2) uses invalid argument names. matrix(1, 2, 3, 4, 2, 2) uses positional arguments without the vector wrapper.m1 <- matrix(c(1, 2, 3, 4), nrow=2, ncol=2, byrow=TRUE) m2 <- matrix(c(5, 6, 7, 8), nrow=2, ncol=2, byrow=TRUE) m3 <- m1 + m2 print(m3)
+ between matrices adds corresponding elements: (1+5), (2+6), (3+7), (4+8).m1 <- matrix(c(1, 2, 3, 4), nrow=2) m2 <- matrix(c(5, 6, 7), nrow=3) m3 <- m1 %*% m2 print(m3)
m1 <- matrix(c(1, 0, 2, -1), nrow=2) m2 <- matrix(c(3, 1, 4, 2), nrow=2)
m1 %*% m2 and then subtract the identity matrix of size 2. Which code correctly does this?%*% to multiply m1 and m2 correctly.diag(2) to create a 2x2 identity matrix and subtract it from the product.Pass the test and this pattern moves unknown