1

I have an array that I have saved it in the MC variable:

with open(PATH_FICHERO1, newline='',  encoding='latin-1') as csvfile:
    data = list(csv.reader(csvfile))
MC=numpy.array([numpy.array(datai) for datai in data])
type(MC)
print(MC)

enter image description here

In the case that there is a letter B I want to change the value for a random value that is between 1/3 and 1. Applying the following code does not give me an error, nevertheless when viewing the matrix the random values are always the same .

B= np.random.uniform(1/3,2/3)
MC = np.where( MC == 'B',B , MC)
print(B)
print(MC)

The values should be the same, in the case of B it is generated randomly but then I don't know why it is not applied in the matrix.

enter image description here

1
  • Please do not post code or data as screenshots. Commented Aug 7, 2021 at 18:29

2 Answers 2

2

By default, np.random.uniform generates ONE random variable. You must pass the shape of the output array if you want an array of random variables:

B = np.random.uniform(1/3, 2/3, MC.shape)
Sign up to request clarification or add additional context in comments.

2 Comments

In case I want the generated matrix to be symmetric what should I do?
Symmetrize the matrix: B=(B+B.T)/2.
1

It looks like the problem is in code.

B= np.random.uniform(1/3,2/3)
MC = np.where( MC == 'B',B , MC)

Above you have assigned the random value to variable B and then mapping the same value to each element in the matrix. e.g. if the random value is 0.55 assigned to variable B then the same value will be mapped to each character in the matrix, that's why you are seeing the same value everywhere.

Solution :-

import numpy as np
MC = [['1', 'B','B','B','B'],['B', '1','B','B','B'],['B', 'B','1','B','B'],['B', 'B','B','1','B'],['B', 'B','B','B','1']]

for i in range(len(MC)):
  for j in range(len(MC[i])):
    if MC[i][j]== "B":
      MC[i][j]=str(np.random.uniform(1/3,2/3))

Result:

[['1',
  '0.4133872881475391',
  '0.388606739011768',
  '0.632669589057151',
  '0.555652072409681'],
 ['0.5964448593391674',
  '1',
  '0.5916592530420399',
  '0.6004173979328635',
  '0.45989982907152327'],
 ['0.49491629056763076',
  '0.5814889531351302',
  '1',
  '0.42177756298000196',
  '0.44166060842279004'],
 ['0.43908913157941704',
  '0.5630605854105761',
  '0.5867510079174598',
  '1',
  '0.5518789342365693'],
 ['0.6008453194037271',
  '0.5921925074432766',
  '0.344618130286966',
  '0.5767303673801853',
  '1']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.