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

Convert Matlab vector to function object in order to integrate it

0 votes

I am trying to import a matlab vector vec.mat ( with a variable X) to fenics and then assign in to a function in a space in order to integrate it. My code looks like :

`from dolfin import *
from dolfin_adjoint import *
import scipy.io as sio

file = sio.loadmat('vec.mat')
my_vec = file['X']

mesh = UnitSquareMesh(4, 4)
V =FunctionSpace(mesh, "CG", 1)
u = Function(V)

u.vector()[:] = numpy.array(my_vec)`

But I am getting the error:
IndexError: expected same size of indices and values
Even though my matlab vector is the same size as the space V.

How can I achieve a match in the indices?

asked Mar 1, 2015 by Katianefs FEniCS Novice (200 points)

1 Answer

+1 vote
 
Best answer

Hi, did you make sure that numpy.array(my_vec) has a correct shape? In the attached code, assigning u_vec rightaway is not possible since the shape is (1, 25) but (25, ) is expected.

from dolfin import *
import scipy.io as io

mesh = UnitSquareMesh(4, 4)
V = FunctionSpace(mesh, 'CG', 1)

u = interpolate(Expression('x[0]+x[1]'), V)

# Save coefficient of u
io.savemat('u_vec.mat', {'u': u.vector().array()})
# Load
mat_file = io.loadmat('u_vec.mat')
u_vec = mat_file['u'] 

# At this point u_vec is
print type(u_vec), u_vec.shape 
# Array of arrays!

u_vec = u_vec[0]
# Now you can assign
u.vector()[:] = u_vec
answered Mar 1, 2015 by MiroK FEniCS Expert (80,920 points)
selected Mar 4, 2015 by Katianefs

Thanks for the solution ! This code however is for CG space of degree 1. What happens if I am using CG degree 2 instead ?

The above code will work for any degree. In any case, make sure that the dof ordering of your matlab vector is the same as the one used by DOLFIN.

Hi MiroK

How can I make the dof ordering of a matlab vector the same as the one used by DOLFIN?

I want to use a matlab array to define a vector function like above but if the ordering of the values in the array is not the same as DOLFIN has it, my function will not have the right values where it should.

Thanks in advance!

...