tags:

views:

62

answers:

3

Basically I have x amount of matrices I need to establish of y by y size. I was hoping to name the matrices: matrixnumber1 matrixnumber2..matrixnumbern

I cannot use an array as its matrices I have to form.

Is it possible to use a string to name a string (or a matrix in this case)?

Thank you in advance for any help on this!

for (int i = 1; i <= numberofmatricesrequired; i++)
        {
        string number = Convert.ToString(i);
        Matrix (matrixnumber+number) = new Matrix(matrixsize, matrixsize);
        }
+2  A: 

If you really want to you could create a Dictionary<String, Matrix> to hold the matrices you create. The string is the name - created however you like.

You can then retrieve the matrix by using dict["matrix1"] (or whatever you've called it).

However an array if you have a predetermined number would be far simpler and you can refer to which ever you want via it's index:

Matrix theOne = matrix[index];

If you have a variable number a List<Matrix> would be simpler and if you always added to the end you could still refer to individual ones by its index.

ChrisF
+3  A: 

You can achieve a similar effect by creating an array of Matrices and storing each Matrix in there.

For example:

Matrix[] matrices = new Matrix[numberofmatricesrequired];
for (int i = 0; i < numberofmatricesrequired; i++)
{
    matrices[i] = new Matrix(matrixsize, matrixsize);
}

This will store a bunch of uniques matrices in the array.

jjnguy
Thank you for your quick response. I tried that initially but I received an error "Index was outside the bounds of the array". So I thought an array of matrices was not possible?
RHodgett
@RHodgett That was probably because you were going from 1 up to the max. You need to go from 0 to the max-1.
jjnguy
Brilliant it worked! The problem was I was starting the loop from 0 "for (int i = 0; i <= (Matrices.Length-1); i++)"Worked Fine! Thank you so much!
RHodgett
@RHodgett Glad I could help!
jjnguy
+1  A: 

I'm curious why you cannot use an array or a List, as it seems like either of those are exactly what you need.

Matrix[] matrices = new Matrix[numberofmatricesrequired];

for (int i = 0; i < matrices.Length; i++)
{
    matrices[i] = new Matrix(matrixsize, matrixsize);
}

If you really want to use a string, then you could use a Dictionary<string, Matrix>, but given your naming scheme it seems like an index-based mechanism (ie. array or List) is better suited. Nonetheless, in the spirit of being comprehensive...

Dictionary<string, Matrix> matrices = new Dictionary<string, Matrix>();

for (int i = 1; i <= numberofmatricesrequired; i++)
{
    matrices.Add("Matrix" + i.ToString(), new Matrix(matrixsize, matrixsize));
}
Adam Robinson
Thank you! Your code helped me solve my problem.
RHodgett