type conversion error, c# - c#

I am using Advanced Matrix Library in C#. NET#
http://www.codeproject.com/KB/recipes/AdvancedMatrixLibrary.aspx?msg=4042613#xx4042613xx.
library css file is like
using System;
namespace MatrixLibrary
{
public class Matrix
{
private double[,] in_Mat;
public Matrix(int noRows, int noCols)
{
this.in_Mat = new double[noRows, noCols];
}
public Matrix(double [,] Mat)
{
this.in_Mat = (double[,])Mat.Clone();
}
public static double[,] Identity(int n)
{
double[,] temp = new double[n,n];
for (int i=0; i<n;i++) temp[i,i] = 1;
return temp;
}
public static double[,] ScalarDivide(double Value, double[,] Mat)
{
int i, j, Rows, Cols;
double[,] sol;
try {Find_R_C(Mat, out Rows, out Cols);}
catch{throw new MatrixNullException();}
sol = new double[Rows+1, Cols+1];
for (i = 0; i<=Rows;i++)
for (j = 0; j<=Cols;j++)
sol[i, j] = Mat[i, j] / Value;
return sol;
}
}}
I am trying to get identity matrix and getting error of type conversion. Could some one please guide me.
Matrix id_mat = MatrixLibrary.Matrix.Identity(6);
Can't implicity convert typedouble[,] to Matrix.
But
Matrix B = new Matrix(4, 4);
Random rnd = new Random();
for (int i = 0; i < B.NoRows; i++)
for (int j = 0; j < B.NoCols; j++)
B[i, j] = 2 * rnd.NextDouble();
Matrix E = Matrix.ScalarDivide(2, B);
It works and I can Have a matrix. Please guide me?
regards,

Read the error message.
You have a method that returns double[,] and you are trying to store the reference in a variable for Matrix. There is no implicit conversion from a multidimensional array of doubles to a Matrix.
To use that method, you would write
double[,] id_max = MatrixLibrary.Maxtrix.Identify(6);
If you actually need to store it as a Matrix, you need to define the appropriate conversion to do so.

The function returns a 2D array "double[,]" and you're trying to assign it to a "Matrix". There isn't an implicit conversion that does this. Does Matrix have a constructor that accepts a "double[,]"? Maybe you could use that.
EDIT: You might also find that a different matrix library would suit you better than one pulled off of CodeProject. Math.NET Numerics is a good one that I've used that's also open source: http://numerics.mathdotnet.com/

You need an implicit cast.
public static implicit operator Matrix(double[,] m)
{
// code to convert
}

Related

Why "foo = new double[int x, int y]" is legal but not "foo = new double[int x][int y]"?

I know there are differences between jagged and multidimensional arrays. I know it is often likeable to use a "List<>" instead of arrays of arrays.
Could someone just explain me why, in the following code, the first is allowed but the second is an error? I just want to better understand C#...
Legal:
public class Banana
{
double[,] _banana;
public Banana(int h, int w)
{
_banana= new double[h,w];
}
}
Illegal (Error: a constant value is expected instead of h and w):
public class Banana
{
double[][] _banana;
public Banana(int h, int w)
{
_banana= new double[h][w]{};
}
}
TL;DR;
Why is it possible to initialize the dimensions of a multi array with variables but not a jagged array's?
An int[4,5] is single object which holds twenty integers. An int[4][] is an object which holds four references to integer arrays. Having int[][] foo = new int[4][5]; be equivalent to:
int[][] foo = new int[4][];
for (int temp = 0; temp < 4; temp++)
foo[i] = new int[5];
would make about as much sense as having StringBuilder bar[] = new StringBuilder[4](); be equivalent to:
StringBuilder bar = new StringBuilder[4];
for (int temp = 0; temp < 4; temp++)
bar[i] = new StringBuilder();
Such a feature might be helpful in many cases, and there wouldn't be anything particularly wrong with it conceptually, but the code required to explicitly initialize array elements isn't particularly onerous, and writing such code explicitly helps make clear that the array-of-references and the things to which those references refers are all separate entities.
With a jagged array you have to initialize each "leg" separately - there's no syntax to initialize the size of each leg in one pass:
public Banana(int h, int w)
{
_banana = new double[h][];
for (int i = 0; i < h; i++)
{
_banana[i] = new double[w];
}
}
Why is there no syntax? Because the spec doesn't require it, and in a "typical" jagged array the legs have different lengths, otherwise a 2-D array may be more appropriate.
Each nested array in a jagged array can have a different length. If you had to initialize it using your syntax example, they would all be required to have the same length. It simply doesn't make sense. You'd have to use something like:
_banana = new double[h][];
for(var i = 0; i < h; i++)
{
_banana[h] = new double[w];
}

Make custom class instances reinstantiate on operator = is it possible?

I have a code like this:
public static IEnumerable<IntEx> FibbonacciNumbersStr()
{
IntEx j = 0;
IntEx i = 1;
for (Int64 k = 0; k < Int64.MaxValue; k++)
{
yield return j;
IntEx oldi = i;
i = i+j;
j = oldi;
}
}
IntEx is a custom 'int' class able to calculate gigantic numbers and write them as string in any given number base, the problem here is, when I say IntEx oldi = i, oldi will be a POINTER to i and ends up not doing its purpose, (thus making that fibonacci sequence totally wrong. Tho, if I do
public static IEnumerable<IntEx> FibbonacciNumbersStr()
{
IntEx j = 0;
IntEx i = 1;
for (Int64 k = 0; k < Int64.MaxValue; k++)
{
yield return j;
IntEx oldi = new IntEx(i);
i = i+j;
j = oldi;
}
}
It works perfectly.
Is there any way I can get the second result using the simple = operator to reinstantiate instead of pointing to, thus imitating better the behavior of Int64 or something?
I mean, the point here is I may end up wanting to distribute this code for other people to work with and they would probably end up having that 'point to instead of being a new value' problem when using IntEx class -_-
Any ideas?
There is no way to override the = behavior in C#. If IntEx is a class type then assignment will always cause the LHS to refer to the same value as the RHS.
This can be solved to a degree by inserting a struct into the equation. In struct assignment are fields are copied memberwise between the LHS and RHS. It still can't be customized but does ensure some separation of the values
you can always create a static method to set a value.
Thus this solutions would work.
IntEx.SetValue(i);
or make the IntEx produce instances not by creating new but making a static method to it like.
IntEx.CreateInstance(i);

Passing one Dimension of a Two Dimensional Array in C#

I have moved from C to C#.
I have a function which accepts an array. I want to pass one dimension of a Two Dimensional array to this function.
C Code would be:-
void array_processing(int * param);
void main()
{
int Client_ID[3][50];
/* Some
Processing
which fills
this array */
array_processing(&Client_ID[1]);
}
Now, When I want to do same in C#, How can I pass this array?
Function defination will look like:-
private void array_processing(ref int[] param);
and Array would be declared as :-
int[,] Client_ID = new int[3,50];
Now How can I pass Client_ID[1] to the function array_processing()??
By doing array_processing ( ref Client_ID[1]) shouts as "Wrong Number of Indices"!
You can't really do that. C# is less outgoing about its arrays, and prevents you from doing C-like manipulations. This is a good thing.
You have various options:
Create a 1D array and copy your 2D row to it.
Use a jagged array - an array of arrays, which is more like what C lets you do.
Have an array_processing overload that takes a 2D array and a row number.
If you really want to access a 2D row as a 1D array, you should create a 'RowProxy' class that will implement the IList interface and let you access just one row:
class RowProxy<T>: IList<T>
{
public RowProxy(T[,] source, int row)
{
_source = source;
_row = row;
}
public T this[int col]
{
get { return _source[_row, col]; }
set { _source[_row, col] = value; }
}
private T[,] _source;
private int _row;
// Implement the rest of the IList interface
}
Use a lambda expression that will lose the array semantics, but is rather cool:
var ClientId = ...;
var row_5_accessor = (c=>ClientId[5, c]);
You can use row_5_accessor as a function, row_5_accessor(3) will give you ClientId[5, 3]
You can use a jagged array
// Initialize jagged array
int[][] clientID = new int[3][];
for (int i=0; i<clientId.Length; i++)
{
clientId[i] = new int[50];
}
array_processing(ref clientId[1]);
And your method:
private void array_processing(ref int[] subArray);
Just declare method
private void ParseArray(int[,] ar)
{
// Some work...
}
UDP: Code format
A primitive way would be:
var dimNumber = 1;
int[] oneDimension = new int[50];
for(var i=0; i<50; i++)
{
oneDimension[i] = Client_ID[dimNumber][i];
}
array_processing ( ref oneDimension);
I would suggest using Lambda expressions like in the way 5 of zmbq's answer.
You could declare you array as
int[][] Client_ID = new[] { new int[50], new int[50], new int[50] };
and then you can pass it to your array_processing function
array_processing(ref Clinet_ID[1]);
Sorry for miss of my pen.
Late to the conversation, but here is a jagged array example to do this:
string[][] rows = GetStringArray(values);
string[] row = rows[0];
You would set up your jagged array something like:
// rowCount from runtime data
stringArray = new string[rowCount][];
for (int index = 0; index < rowCount; index++)
{
// columnCount from runtime data
stringArray[index] = new string[columnCount];
for (int index2 = 0; index2 < columnCount; index2++)
{
// value from runtime data
stringArray[index][index2] = value;
}
}

Use of unassigned out parameter, c#

I have very simple problem.
I made a very simple function for you to demonstrate my problem.
static void Main(string[] args)
{
double[,] mydouble = new double[1, 4];
mynewMatrix(out mydouble);
}
public static void mynewMatrix(out double[,] d)
{
for (int i = 0; i < 4; i++)
d[0, i] = i;
}
Error:
Use of unassigned out parameter 'newMAt' The out parameter 'newMAt'
must be assigned to before control leaves the current method
I don't know where is problem.
If the array is defined OUTSIDE of the function, you should use a ref (or nothing, considering the array is a reference type). out means the parameter will be initialized in the function before it returns. Some examples of use:
static void Main(string[] args)
{
double[,] mydouble;
mynewMatrix(out mydouble);// call of method
double[,] mydouble2 = new double[1, 4];
mynewMatrix2(mydouble2);// call of method
// useless for what you want to do
mynewMatrix3(ref mydouble2);// call of method
}
public static void mynewMatrix(out double[,] d)
{
d = new double[1, 4];
for (int i = 0; i < 4; i++)
{
d[0, i] = i;
}
}
public static void mynewMatrix2(double[,] d)
{
for (int i = 0; i < 4; i++)
{
d[0, i] = i;
}
}
// useless for what you want to do
public static void mynewMatrix3(ref double[,] d)
{
for (int i = 0; i < 4; i++)
{
d[0, i] = i;
}
}
I'll add that if you don't know what is the difference between ref and out you could read Difference between ref and out parameters in .NET
In c# there are two very similar keywords, ref and out.
Both of them pass values by reference, but the difference is:
When you use ref the compiler will require you to assign your variable prior to calling the method.
When using out it will not require this. This means that you will not be able to assume that the parameter has already been populated. You will not be able to read its value inside the method.
To illustrate the problem, just imagine what would happen if someone else wrote this code to call your method:
double[,] myUnassignedDouble;
mynewMatrix(out myUnassignedDouble);
Clearly the variable will never be assigned, which is bad.
This leaves you with three options:
Assign the variable each time you call the method and use void mynewMatrix(ref double[,] d)
Assign the variable once, inside your method and use void mynewMatrix(out double[,] d)
Assign the variable each time you call the method and use void mynewMatrix(double[,] d)
The third option will work because so far you don't seam to need to reassign your variable. Obviously that might change as your code becomes more complicated. I assume you did have your reasons for using out in the first place?
The error message is clear - you need to assign a value to your out parameter inside your method:
public static void mynewMatrix(out double[,] d)
{
d = new double[1, 4];
for (int i = 0; i < 4; i++)
{
d[0,i]=i;
}
}
The assignment you made outside the method has no effect. Just write this:
static void Main(string[] args)
{
double[,] mydouble;
mynewMatrix(out mydouble);
}
You are assigning values to the elements of your array parameter, but you have to assign y value to the array itself because its defined as out:
d = new double[1, 4];

Array of array initialization by using unmanaged pointers in C#

I would like to define an array of array eg int[][] on top of an existing int[] of the right size. I want then to seamlessy use either the int[][] array of array or the int[] 'big' array while refering to the same inner data.
Is this possible to do this in C# using unmanaged code? In C++ I would defined pointers like this :
int* bigArray = new int[numberOfRows * numberOfColumns];
int** matrix = new int*[numberOfRows];
for (int i = 0; i < numberOfRows; i ++)
{
matrix[i] = (bigArray + i * numberOfColumns);
}
Yes, you can also use pointer in C#, but there are some limits on it. 1st, you need to declare the function with unsafe, and also, you need to set the build option to allow unsafe code in the project property, here is the sample code about it:
unsafe static void T1(int numberOfRows, int numberOfColumns)
{
int* bigArray = stackalloc int[numberOfRows * numberOfColumns];
int** matrix = stackalloc int*[numberOfRows];
for (int i = 0; i < numberOfRows; i++)
{
matrix[i] = (bigArray + i * numberOfColumns);
}
}
Remember, you can use the pointer only if you are so clear of that you have full control of your code. while it is not recommend you use the pointer in C#
You can do it in managed code, using a class as a wrapper and providing it with an indexer:
class Matrix
{
public readonly int[] BigArray; // make available
private int _rowSize = ...;
public int this[int x, int y]
{
get { return BigArray [x*_rowSize+y]; }
set { BigArray [x*_rowSize+y] = value; }
}
}
Edit:
changed arrray into public readonly field so that the class has a dual interface
Edit 2:
Using T[][] to provide access to T[] rows.
class Matrix2<T>
{
private T[][] _data;
private int _columns;
public Matrix2(int rows, int cols)
{
_data = new T[rows][];
_columns = cols;
for (int i = 0; i < rows; i++) _data[i] = new T[cols];
}
public T this [int x]
{
get { return _data [x/_columns][x % _columns]; }
set { _data [x/_columns][x % _columns] = value; }
}
public T[] Row(int r)
{
return _data [r];
}
}

Categories

Resources