Is there a way to print a particular value within a matrix using Python, specifically with the help of numpy?

I am facing an issue with a code snippet that is supposed to generate a zero matrix based on a given size (m x n). However, my goal is to extract a specific value from a particular location within that matrix. Despite trying numerous approaches, I have not been able to achieve the desired outcome. Below is the code in question:

import numpy as np 

class Matrix:

def __init__(self, m, n):
  self.row = m
  self.column = n

def define_matrix(self):
  return np.zeros((self.row, self.column), dtype=int)

def __str__(self):
  return self.define_matrix()

...

a = Matrix(4, 4) # matrix could be any size
a.set(80, 1, 3)
a.get(1, 3)

Upon executing the code, the output does not match my expectations.

Answer №1

import numpy as np 

class Matrix:
    
    def __init__(self, rows, columns):
      self.rows = rows
      self.columns = columns
      self.matrix_data = np.zeros((self.rows, self.columns), dtype=int)

    def define_matrix(self):
      return str(self.matrix_data)

    def __str__(self):
      return str(self.define_matrix())

    def get_value(self, row_num, col_num):
      try:
        if not row_num in range(self.rows+1):
          print('The desired value does not belong to the matrix.')
        elif not col_num in range(self.columns+1):
          print('The desired value does not belong to the matrix.')
        else:
          print(
            'The value located at row {} '
            'and column {} is: {}'
            .format(row_num, col_num, self.matrix_data[row_num - 1][col_num - 1]))
      except:
        print('Enter valid data')

    def set_value(self, new_value, row_num, col_num):
      if not row_num in range(self.rows+1):
        print('The desired value does not belong to the matrix.')
      elif not col_num in range(self.columns+1):
        print('The desired value does not belong to the matrix.')
      else:
        self.matrix_data[row_num-1][col_num-1] = new_value
        return self.matrix_data

m = Matrix(4, 4) # matrix can be of any size
m.set_value(80, 1, 3)
m.get_value(1, 3)

I hope this revised code aligns with your expectations!

Answer №2

The issue at hand arises when you invoke

self.define_matrix()[a - 1][b - 1])
inside the get function.

This means that no matter what value is stored in your matrix using the set function, it will always display the initial '0' generated when creating the matrix with

np.zeros((self.row, self.column), dtype=int)
.

Answer №3

Check out this snippet:

import numpy as np
import matplotlib.pyplot as plt

print(np.ones((5, 5)))

Feel free to adjust the dimensions of the matrix to suit your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered CSRF validation error while working with a Python Django backend in conjunction with React frontend using Axios for making POST requests

I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function ...

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

What's the best way to determine which of the two forms has been submitted in Django?

On my homepage, I have both a log_in and sign_up form. Initially, the log_in form is displayed by default, but when a user clicks on the Sign Up button, the sign_up form appears. These toggles switch depending on which button the user clicks. from django ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Learn how to retrieve values from a .json file in real-time and then perform comparisons with user input using Python

I have a JSON file structured like this: [ { "name": { "common": "Aruba", "official": "Aruba", "native": { "nld": { "official ...

Exploring the capabilities of arrays within Ajax

Below is the original code I wrote in JavaScript: var wt_val = []; for (i = 0; i<human_wt.length; i++){ var mult; mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100)); wt_val.push(mult); ...

Invoke a Python function from JavaScript

As I ask this question, I acknowledge that it may have been asked many times before. If I missed the answers due to my ignorance, I apologize. I have a hosting plan that restricts me from installing Django, which provided a convenient way to set up a REST ...

Building a matrix-esque table using d3.js reminiscent of HTML tables

I would like to generate a table resembling a matrix without numerical values. 1. Here is an example of my database table: | CODE | STIL | SUBSTIL | PRODUS | |------|-------|----------|---------| | R | stil1 | substil1 | produs1 | | R | stil1 | s ...

Flask does not provide a direct boolean value for checkboxes

After struggling for a week, I am still lost on where to make changes in my code. I need the checkbox to return a boolean value in my Flask application. Below are snippets of the relevant code: mycode.py import os, sqlite3 from flask import Flask, flash ...