Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/interfaces/matlab.py
4045 views
1
r"""
2
Interface to MATLAB
3
4
According to their website, MATLAB is "a high-level language and
5
interactive environment that enables you to perform computationally
6
intensive tasks faster than with traditional programming languages
7
such as C, C++, and Fortran."
8
9
The commands in this section only work if you have the "matlab"
10
interpreter installed and available in your PATH. It's not
11
necessary to install any special Sage packages.
12
13
EXAMPLES::
14
15
sage: matlab.eval('2+2') # optional
16
'\nans =\n\n 4\n'
17
18
::
19
20
sage: a = matlab(10) # optional
21
sage: a**10 # optional
22
1.0000e+10
23
24
AUTHORS:
25
26
- William Stein (2006-10-11)
27
28
Tutorial
29
--------
30
31
EXAMPLES::
32
33
sage: matlab('4+10') # optional
34
14
35
sage: matlab('date') # optional; random output
36
18-Oct-2006
37
sage: matlab('5*10 + 6') # optional
38
56
39
sage: matlab('(6+6)/3') # optional
40
4
41
sage: matlab('9')^2 # optional
42
81
43
sage: a = matlab(10); b = matlab(20); c = matlab(30) # optional
44
sage: avg = (a+b+c)/3 # optional
45
sage: avg # optional
46
20
47
sage: parent(avg) # optional
48
Matlab
49
50
::
51
52
sage: my_scalar = matlab('3.1415') # optional
53
sage: my_scalar # optional
54
3.1415
55
sage: my_vector1 = matlab('[1,5,7]') # optional
56
sage: my_vector1 # optional
57
1 5 7
58
sage: my_vector2 = matlab('[1;5;7]') # optional
59
sage: my_vector2 # optional
60
1
61
5
62
7
63
sage: my_vector1 * my_vector2 # optional
64
75
65
66
::
67
68
sage: row_vector1 = matlab('[1 2 3]') # optional
69
sage: row_vector2 = matlab('[3 2 1]') # optional
70
sage: matrix_from_row_vec = matlab('[%s; %s]'%(row_vector1.name(), row_vector2.name())) # optional
71
sage: matrix_from_row_vec # optional
72
1 2 3
73
3 2 1
74
75
::
76
77
sage: column_vector1 = matlab('[1;3]') # optional
78
sage: column_vector2 = matlab('[2;8]') # optional
79
sage: matrix_from_col_vec = matlab('[%s %s]'%(column_vector1.name(), column_vector2.name())) # optional
80
sage: matrix_from_col_vec # optional
81
1 2
82
3 8
83
84
::
85
86
sage: my_matrix = matlab('[8, 12, 19; 7, 3, 2; 12, 4, 23; 8, 1, 1]') # optional
87
sage: my_matrix # optional
88
8 12 19
89
7 3 2
90
12 4 23
91
8 1 1
92
93
::
94
95
sage: combined_matrix = matlab('[%s, %s]'%(my_matrix.name(), my_matrix.name())) # optional
96
sage: combined_matrix # optional
97
8 12 19 8 12 19
98
7 3 2 7 3 2
99
12 4 23 12 4 23
100
8 1 1 8 1 1
101
102
::
103
104
sage: tm = matlab('0.5:2:10') # optional
105
sage: tm # optional
106
0.5000 2.5000 4.5000 6.5000 8.5000
107
108
::
109
110
sage: my_vector1 = matlab('[1,5,7]') # optional
111
sage: my_vector1(1) # optional
112
1
113
sage: my_vector1(2) # optional
114
5
115
sage: my_vector1(3) # optional
116
7
117
118
Matrix indexing works as follows::
119
120
sage: my_matrix = matlab('[8, 12, 19; 7, 3, 2; 12, 4, 23; 8, 1, 1]') # optional
121
sage: my_matrix(3,2) # optional
122
4
123
124
Setting using parenthesis cannot work (because of how the Python
125
language works). Use square brackets or the set function::
126
127
sage: my_matrix = matlab('[8, 12, 19; 7, 3, 2; 12, 4, 23; 8, 1, 1]') # optional
128
sage: my_matrix.set(2,3, 1999) # optional
129
sage: my_matrix # optional
130
8 12 19
131
7 3 1999
132
12 4 23
133
8 1 1
134
"""
135
136
##############################################################################
137
# Copyright (C) 2006 William Stein <[email protected]>
138
#
139
# Distributed under the terms of the GNU General Public License (GPL).
140
#
141
# This code is distributed in the hope that it will be useful,
142
# but WITHOUT ANY WARRANTY; without even the implied warranty of
143
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
144
# General Public License for more details.
145
#
146
# The full text of the GPL is available at:
147
#
148
# http://www.gnu.org/licenses/
149
##############################################################################
150
151
import os
152
153
from expect import Expect, ExpectElement
154
155
156
#import sage.matrix.matrix_space
157
158
class Matlab(Expect):
159
"""
160
Interface to the Matlab interpreter.
161
162
EXAMPLES::
163
164
sage: a = matlab('[ 1, 1, 2; 3, 5, 8; 13, 21, 33 ]') # optional
165
sage: b = matlab('[ 1; 3; 13]') # optional
166
sage: c = a * b # optional
167
sage: print c # optional
168
30
169
122
170
505
171
"""
172
def __init__(self, maxread=100, script_subdirectory="",
173
logfile=None, server=None,server_tmpdir=None):
174
Expect.__init__(self,
175
name = 'matlab',
176
prompt = '>> ',
177
command = "sage-native-execute matlab -nodisplay",
178
maxread = maxread,
179
server = server,
180
server_tmpdir = server_tmpdir,
181
script_subdirectory = script_subdirectory,
182
restart_on_ctrlc = False,
183
verbose_start = False,
184
logfile = logfile,
185
eval_using_file_cutoff=100)
186
187
def __reduce__(self):
188
return reduce_load_Matlab, tuple([])
189
190
def _read_in_file_command(self, filename):
191
"""
192
Returns the command used to read in and execute a file in Matlab.
193
194
EXAMPLES::
195
196
sage: matlab._read_in_file_command('/tmp/matlab_file')
197
"eval(fileread('/tmp/matlab_file'));"
198
199
Here is an indirect doctest to check that it does indeed
200
work::
201
202
sage: m = identity_matrix(ZZ, 10)
203
sage: sm = matlab.sage2matlab_matrix_string(m)
204
sage: m = matlab(sm) #optional - matlab
205
"""
206
return "eval(fileread('%s'));"%filename
207
208
def _quit_string(self):
209
return 'quit;'
210
211
def _install_hints(self):
212
return """
213
You must obtain the program MATLAB in order to use MATLAB
214
from Sage. You can read all about MATLAB at
215
http://www.mathworks.com/
216
217
You might have to buy MATLAB or get away with setting up a remote connection to a server running Maple. Type
218
print matlab._install_hints_ssh()
219
for hints on how to do that).
220
"""
221
222
def _start(self):
223
Expect._start(self)
224
225
def whos(self):
226
return self.eval('whos')
227
228
# pdehaye/20070819: This is no obsolete, see Expect._get_tmpfile_from_server and Expect._send_tmpfile_to_server
229
230
# def get_via_file(self, var_name):
231
# t = self._temp_file(var_name)
232
# self.eval('save -text "%s" %s'%(t,var_name))
233
# r = open(t).read()
234
# os.unlink(t)
235
# return r.strip('\n')
236
237
# def set_via_file(self, var_name, x):
238
# t = self._temp_file(var_name)
239
# open(t,'w').write(x)
240
# print 'load "%s" %s'%(t, var_name)
241
# self.eval('load "%s" %s'%(t, var_name))
242
# #os.unlink(t)
243
244
def set(self, var, value):
245
"""
246
Set the variable var to the given value.
247
"""
248
cmd = '%s=%s;'%(var,value)
249
out = self.eval(cmd)
250
if out.find("error") != -1:
251
raise TypeError, "Error executing code in Matlab\nCODE:\n\t%s\nMatlab ERROR:\n\t%s"%(cmd, out)
252
253
def get(self, var):
254
"""
255
Get the value of the variable var.
256
257
EXAMPLES::
258
259
sage: s = matlab.eval('a = 2') #optional - requires matlab
260
sage: matlab.get('a') #optional
261
' 2'
262
"""
263
s = self.eval('%s'%var)
264
return self.strip_answer(s)
265
266
def strip_answer(self, s):
267
r"""
268
Returns the string s with Matlab's answer prompt removed.
269
270
EXAMPLES::
271
272
sage: s = '\nans =\n\n 2\n'
273
sage: matlab.strip_answer(s)
274
' 2'
275
"""
276
i = s.find('=')
277
return s[i+1:].strip('\n')
278
279
280
def console(self):
281
matlab_console()
282
283
def version(self):
284
return matlab_version()[1:]
285
286
def chdir(self, directory):
287
"""
288
Change MATLAB's current working directory.
289
290
EXAMPLES::
291
292
sage: matlab.chdir('/') # optional - matlab
293
sage: matlab.pwd() # optional - matlab
294
/
295
296
"""
297
self.eval("cd('%s')"%directory)
298
299
def sage2matlab_matrix_string(self, A):
300
"""
301
Return an matlab matrix from a Sage matrix.
302
303
INPUT: A Sage matrix with entries in the rationals or reals.
304
305
OUTPUT: A string that evaluates to an Matlab matrix.
306
307
EXAMPLES::
308
309
sage: M33 = MatrixSpace(QQ,3,3)
310
sage: A = M33([1,2,3,4,5,6,7,8,0])
311
sage: matlab.sage2matlab_matrix_string(A) # requires optional matlab
312
'[1, 2, 3; 4, 5, 6; 7, 8, 0]'
313
314
AUTHOR:
315
316
- David Joyner and William Stein
317
"""
318
return str(A.rows()).replace('), (', '; ').replace('(', '').replace(')','')
319
320
def _object_class(self):
321
return MatlabElement
322
323
324
class MatlabElement(ExpectElement):
325
def __getitem__(self, n):
326
raise RuntimeError, "Use parenthesis for MATLAB matrices instead."
327
328
def _matrix_(self, R):
329
r"""
330
Return Sage matrix from this matlab element.
331
332
EXAMPLES::
333
334
sage: A = matlab('[1,2;3,4]') # optional matlab package
335
sage: matrix(ZZ, A) # optional
336
[1 2]
337
[3 4]
338
sage: A = matlab('[1,2;3,4.5]') # optional matlab package
339
sage: matrix(RR, A) # optional
340
[1.00000000000000 2.00000000000000]
341
[3.00000000000000 4.50000000000000]
342
343
sage: a = matlab('eye(50)') #optional - requires matlab
344
sage: matrix(RR, a) #optional - requires matlab
345
50 x 50 dense matrix over Real Field with 53 bits of precision
346
347
"""
348
from sage.matrix.all import matrix
349
matlab = self.parent()
350
entries = matlab.strip_answer(matlab.eval("mat2str(%s)"%self.name()))
351
entries = entries.strip()[1:-1].replace(';', ' ')
352
entries = map(R, entries.split(' '))
353
nrows, ncols = map(int, str(self.size()).strip().split())
354
m = matrix(R, nrows, ncols, entries)
355
return m
356
357
def set(self, i, j, x):
358
P = self._check_valid()
359
z = P(x)
360
P.eval('%s(%s,%s) = %s'%(self.name(), i, j, z.name()))
361
362
# An instance
363
matlab = Matlab(script_subdirectory='user')
364
365
def reduce_load_Matlab():
366
return matlab
367
368
369
import os
370
def matlab_console():
371
"""
372
This requires that the optional matlab program be installed and in
373
your PATH, but no optional Sage packages need be installed.
374
375
EXAMPLES::
376
377
sage: matlab_console() # optional and not tested
378
< M A T L A B >
379
Copyright 1984-2006 The MathWorks, Inc.
380
...
381
>> 2+3
382
383
ans =
384
385
5
386
387
quit
388
389
Typing quit exits the matlab console and returns you to Sage.
390
matlab, like Sage, remembers its history from one session to
391
another.
392
"""
393
os.system('matlab -nodisplay')
394
395
396
def matlab_version():
397
"""
398
Return the version of Matlab installed.
399
400
EXAMPLES::
401
402
sage: matlab_version() # random optional matlab package
403
'7.2.0.283 (R2006a)'
404
"""
405
return str(matlab('version')).strip()
406
407
408