OneCompiler

urkurk M

164
 
matrix =[[1, 2, 3],[4, 5, 6]]# Adding a row
matrix.append([7, 8, 9])



for row in matrix:# Adding a column
    row.append(0)  # Adds a new column with 0 in each row


 
matrix[0][1] = 20# Change the element in the first row, second column  



row_sum = 0# Sum of elements in the first row
for element in matrix[0]:
    row_sum += element



def my_function(L, i, j): #return the sum of specific colums
      
      
    total = 0
  if not L or i > j:# Check matrix L is empty or if i > j (invalid range)
      return 0  
  for row in L:# Iterate over each row in the matrix
       # Sum the elements from column i to column j (inclusive)
      total += sum(row[i:j + 1])
  
  
  return total # Return the final total sum
    
    

def transpose_row_col(M, i, j):# transpose bytte row med columns
    M (list of lists): The input square matrix.
    i (int): The index of the row to be swapped.
    j (int): The index of the column to be swapped.
    
    for k in range(len(M)):  # Iterate over all rows/columns
        # Swap the elements in row `i` and column `j`
        M[i][k], M[k][j] = M[k][j], M[i][k]
         # Use a temporary variable to swap the elements in row `i` and column `j`
        temp = M[i][k]
        M[i][k] = M[k][j]
        M[k][j] = temp
    return M
       
       

def set_upper_triangle(M, val):# forandrer de øverste diagonal med val

  for row in range(len(M)):  # Iterate through each row
    for col in range(row + 1, len(M)):  # Target only elements above the diagonal
      M[row][col] = val  # Replace with the given value
  return M  # Return the updated matrix



def replace_diagonal(M, i, val):#replaces elements on a diagonal 
  for row in range(len(M)):  # Iterate through each row of the matrix
    if i == 0:  # If i is 0, target the main diagonal
      M[row][row] = val  # Replace the element at position [row][row] (main diagonal)
    elif i == 1:  # If i is 1, target the secondary diagonal
        # Replace the element at position [row][len(M) - 1 - row] (secondary diagonal)
        M[row][len(M) - 1 - row] = val
    return M  # Return the modified matrix