Quantcast
Channel: Math.NET Numerics
Viewing all articles
Browse latest Browse all 971

New Post: Help with Matrix XmlSerialization

$
0
0
Hi,

I need to serialize a Matriz in order to store it in the database. Currently I'm trying to do this using XmlSerializer, but its throwing InvalidOperationException:
MathNet.Numerics.LinearAlgebra.Complex.DenseMatrix cannot be serialized because it does not have a parameterless constructor
Here's a piece of my code:
// MathNet version 2.6.0.29
// Framework 4.5
// Visual Studio 2012
// WCF

static void Main(string[] args)
{
    Type t = Type.GetType("MathNet.Numerics.LinearAlgebra.Complex.Matrix");
    var matrix = createMatrix();
    string xml = serializeToXML(matrix, t);
}

private Matrix createMatrix()
{
    DenseMatrix dm = new DenseMatrix(10,10);
    // populate cells ...
    return (Matrix)dm;
}

private string serializeToXML(object obj, Type type)
{

    using (MemoryStream ms = new MemoryStream())
    {

        object oConv; 

        XmlSerializer serializer = serializer = new XmlSerializer(type);

        #region 'cast from DenseMatrix to Matrix'
        MethodInfo castMethod = typeof(SerializationHelper).GetMethod("Cast", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(type);
        oConv = castMethod.Invoke(null, new object[] { obj });
        #endregion 
        
        XmlWriterSettings xmlSettings = new XmlWriterSettings();
        xmlSettings.OmitXmlDeclaration = true;

        XmlWriter xml = XmlWriter.Create(ms, xmlSettings);

        try
        {
                        // this line throws the exception 
            serializer.Serialize(xml, oConv); 

            //also tried with direct cast like this:
            serializer.Serialize(xml, (Matrix)obj); 

        }
        catch (Exception)
        {
            throw;
        }

        byte[] bytes = ms.ToArray();
        string ret = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
        return ret;

    }

}

private static T Cast<T>(object o)
{
    return (T)o;
}
How can I do this serialization?


Thanks in regards!

Viewing all articles
Browse latest Browse all 971

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>