This is a read only copy of the old FEniCS QA forum. Please visit the new QA forum to ask questions

How to import matrix in matlab to Fenics

+2 votes

I would like to compare my results of Matlab and Fenics. So I need to transport one result to another program. I wanna learn how to import or export an matrix or vector from fenics to Matlab?
Thank you

asked Apr 9, 2014 by hiegilmez FEniCS Novice (210 points)

2 Answers

+4 votes

If you use the Python interface dolfin to FEniCS, you can simply use the functions of Scipy's io module to read and write mat files.

An assembled form M you can export to a sparse matrix like

import scipy.sparse as sps
dolfin.parameters.linear_algebra_backend = "uBLAS"
rows, cols, values = M.data()
Ma = sps.csr_matrix((values, cols, rows))

A function u you becomes an array like

ua = u.vector().array()

If you want to go the other way round, assign the vector array to a dolfin function u using the vector().setlocal of u. However, I don't know how to convert back a sparse matrix to an assembled form.

answered Apr 9, 2014 by Jan FEniCS User (8,290 points)
edited Apr 9, 2014 by Jan
+4 votes

You may also import Matlab (or its free version Octave)
into Python and do everything there.

See:
http://hplgit.github.io/fenics-mixed/doc/pub/sphinx-cbc/._part0002_fenics-mixed.html

answered Apr 11, 2014 by Kent-Andre Mardal FEniCS Expert (14,380 points)
...