Raady
Raady

Reputation: 1726

generate a matrix with random zeros

Using C I am trying to generate a matrix which has to have more number of zero elements than non zero elements. The zero elements should be random how to generate it.

I am able to generate random numbers with some elements as zero, but the zero elements should be more than non-zero elements

int main(){
     srand(time(NULL));
     int array[25];
     int i;
     for (i=0;i<s;i++){
         if (rand()%3 == 0)
              array[i]=rand()%3;
         else
              array[i] = rand();
     }
 }

is the generated matrix sparse matrix ? how can I understand the difference ?

Upvotes: 1

Views: 157

Answers (1)

Caleb
Caleb

Reputation: 930

I assume you’d want no more than 10% of the matrix with non-zero values? Probably a lot less if you have a true sparse matrix that is large (thousands or millions of elements).

I would actually not go the route you are going. I would first init the array to all zeros. You can do that with int myArray[25] = {0} or with memset.

Once you have that, you can then calculate how many non-zero elements you need. If you have 30 elements and want 10% non-zero elements, you need to fill in 3 elements. You can google around and find out how to use srand to calculate which indices to place the non-zero elements at.

Once you have those, you can use srand again to get and set the actual values to fill in.

I have purposely not given a lot of details here, just a general direction I would take. It would probably be good to try a few things out and also provide code examples that actually compile (your example does not, there are a few variables that aren’t defined).

Upvotes: 2

Related Questions