Help Creating A Random Matrix

Hi Guys,

I am trying to create a random matrix where the user inputs the size and then the program outputs a square matrix that size but the values of the matrix are all random. I am using newmat to accomplish this. Here is my code, can you tell me whats wrong? I am told that C is not initialized which I can see but I am not sure what to do to fix this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

float get_uniform()
{
return (((float) rand())/((float) RAND_MAX));
}

void create_random_matrix( double **A, int n)

{
	
	int i, j;
	for (i = 0; i < n; i++) 
		for (j = 0; j < n; j++) 
			A[i][j] = get_uniform();
		cout << A << endl;
}


int main()
{
	int n;
	double **C;
	cout << "matrix size? " << endl;
	cin >> n;
	create_random_matrix (C,n);
}



Any help is greatly appreciated.
Last edited on
Please please please help me guys!!

I am still very new to C++ and struggle with this stuff way to often...
I think you want:
1
2
const int N = ...;
double c[N][N];

But you can't pass that to a function unless the function knows N at compile time...!
I need n to be an input from the user though.... It can't be equal to something ahead of time can it? I could initialize it to zero and then have the user replace it, is that what you mean? Am I even correct in my confusion here?
I'm also using part of a code provided to me by my professor and that's why I have C and A as pointers (I think that's what they are...). I tried having them be set as matrices but then I get a problem with:

 
A[i][j] = get_uniform();
If they need to be dynamically allocated at runtime then you can use the (hackish)
1
2
3
4
5
6
7
8
9
double **c = new double*[n]; //allocate an array of double pointers of n length, and store a pointer to it in c
for( int i = 0; i < n; i++ )
    c[i] = new double[n]; //allocate an array of doubles of n length and store a pointer to it in c[i]
//Now initialize c with values.
//...
//Later, when your done with c, clear up memory...
for( int i = 0; i < n; i++ )
    delete[] c[i];
delete[] c;

There are better ways, but this may be the easiest that works for you.
Topic archived. No new replies allowed.