2

I am very new to Python, and I have to make some changes to existing project at work. I am importing data from Matlab binary data file into my Python script.

lets say original *.m file contains something like this:

> Temperature=61.3
> 
> VibrationSamples=[76,75,76,77, ... a lot of samples, 78]
>
> save(filename.mat, 'Temperature', 'VibrationSamples', '-mat7-binary')

(This is the minimal example I can provide)

I import resulting *.mat into the python script using

> mat = scipy.io.loadmat(filename.mat)

After that I am able to access elements from my matlab structure by using

> variableA = mat('temperature')
> variableB = mat('vibrationSamples')

However I am confused with the result. If I try to print varialbeA, for given example it will come up with two-dimensional array. The output of print variableA is [[61.3]]. In *.m file it is clearly float.

Why is this happening. What is clean way to resolve it? I know I can just use

> variableA = mat('temperature')[0][0]

But this does not look appropriate.

Am I doing something wrong?

2
  • 1
    That's how MATLAB stores values isn't it? It doesn't have scalars, only arrays. Commented Jul 1, 2014 at 9:52
  • Oh, I forgot to mention, that I am a total n00b in MATLAB too. So what would be the appropriate solution? Address values with index[0] as I described in the question? Or do the cast like float() or something else? Commented Jul 1, 2014 at 9:54

1 Answer 1

3

That's just how MATLAB stores scalars. In the MATLAB data model, scalars are represented as 1 by 1 arrays.

So in Python you would pull out the value like this:

mat['Temperature'][0,0]

More information on the MATLAB side of this issue can be found here: http://www.mathworks.co.uk/help/matlab/math/empty-matrices-scalars-and-vectors.html#f1-86433

Scalars

Any individual real or complex number is represented in MATLAB as a 1-by-1 matrix called a scalar value:

A = 5;

ndims(A)        % Check number of dimensions in A
ans =
     2

size(A)         % Check value of row and column dimensions
ans =
     1     1

Use the isscalar function to tell if a variable holds a scalar value:

isscalar(A)
ans =
    1
Sign up to request clarification or add additional context in comments.

1 Comment

Good explanation. Exactly what I needed. I will only add, that for integers and floats, casting does the same job as addressing using indexes. For example, float(mat['Temperature']) will have the same result as mat['Temperature'][0][0]. This won'e work for strings though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.