Help Creating Random Matrix Needed

Hi Guys,

I am trying to create a random matrix. I am using Newmat10 and its appropriate libraries. I am not sure how to create a random matrix though. Here is what I have been trying:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Matrix create_random_matrix(Matrix D, int n,int k)

{
	int i, j;
	int T;
	Matrix A(n,n);
	cout << endl;
	cout << "---------------";
	
	for (i = 1; i < n; i++) {
		cout << endl;;
		for (j = 1; j < n; j++){
			T=rand()% 100 +1;
			A(i,j) = T;
			cout << A << "\t";
		}
	}
	cout<<A<<endl;
	return A;
	
	cout << endl;
	cout << "---------------";
}


I ask the user to input n and k in the main code so it can be any size but it will always be square. Thank you in advance for any help you can provide.
Last edited on
closed account (DGvMDjzh)
Looks like it works to me. 2 ; in line 11, early return that stops 21 and 22 from happening, but nothing fatal. What's the problem? Is there an error, or is the matrix not random enough?
Doesn't look very random to me, actually. You should seed your rand outside of the for loop instead of repeatedly seeding it inside of the for loop.
It doesn't return good values. I get something like 41, -41.00000, 25694839729834819234000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000000 and
-25694839729834819234000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000000

......
closed account (DGvMDjzh)
I'm not sure how exactly your matrix class handles to describe a 2D arrays in a single integer. But I assume it's suppose to look something like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int** create_random_matrix(int x,int y) {
 int A[x][y];
 int i1, i2;
 cout << endl;
 cout << "---------------";

 for (i1 = 0; i1 < x; i1++) {
  cout << endl;;
  for (i2 = 0; i2 < y; i2++) {
   A[i1][i2] = rand()% 100 + 1;
   cout << A[i1][i2] << "\t";
  }
 }

 cout << endl;
 cout << "---------------";
 return (int**)A;
}
Last edited on
My initial question still remains. I need to keep everything in the matrix class.
closed account (DGvMDjzh)
Oh sorry. Well, the reason is obviously because you're trying to print an entire array as a single number which makes no sense. Another problem is that I have no idea how your Matrix class works.

cout << A << "\t"; This is doubtfully the right way to return the specific destination

cout << A[i][j] << "\t"; If A does return an array this is the way to go

If this fails try to find a function or variable in your class that handles the array.
cout << A.getarray(i,j) << "\t";
Perhaps..?

Good luck.
Topic archived. No new replies allowed.