当前位置: 首页>>代码示例>>Python>>正文


Python Matlab.get_variable方法代码示例

本文整理汇总了Python中pymatbridge.Matlab.get_variable方法的典型用法代码示例。如果您正苦于以下问题:Python Matlab.get_variable方法的具体用法?Python Matlab.get_variable怎么用?Python Matlab.get_variable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pymatbridge.Matlab的用法示例。


在下文中一共展示了Matlab.get_variable方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import get_variable [as 别名]
class MATLAB:

    def __init__(self):
        print "Initializing MATLAB."
        self.mlab = Matlab()
        print "Done initializing MATLAB."

    def connect(self):
        self.mlab.start()

    def disconnect(self):
        if(self.mlab.started):
            self.mlab.stop()
        else:
            print "Tried to disconnect from MATLAB without being connected."

    def run_code(self, code):

        try:
            r = self.mlab.run_code(code)
        except Exception as exc:
            raise RuntimeError("Problem executing matlab code: %s" % exc)
        else:
            if(not r['success']):
                raise RuntimeError(
                    "Problem executing matlab code: %s: %s" % (code, r['content']))

    def getvalue(self, var):
        return self.mlab.get_variable(var)
开发者ID:wonkykludge,项目名称:fsspmnl,代码行数:31,代码来源:MATLAB.py

示例2: list

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import get_variable [as 别名]
        w = pywt.Wavelet(wavelet)
        mlab.set_variable('wavelet', wavelet)
        if size_set == 'full':
            data_sizes = list(range(w.dec_len, 40)) + \
                [100, 200, 500, 1000, 50000]
        else:
            data_sizes = (w.dec_len, w.dec_len + 1)
        for N in data_sizes:
            data = rstate.randn(N)
            mlab.set_variable('data', data)
            for pmode, mmode in modes:
                # Matlab result
                mlab_code = ("[ma, md] = dwt(data, wavelet, "
                             "'mode', '%s');" % mmode)
                res = mlab.run_code(mlab_code)
                if not res['success']:
                    raise RuntimeError(
                        "Matlab failed to execute the provided code. "
                        "Check that the wavelet toolbox is installed.")
                # need np.asarray because sometimes the output is type float
                ma = np.asarray(mlab.get_variable('ma'))
                md = np.asarray(mlab.get_variable('md'))
                ma_key = '_'.join([mmode, wavelet, str(N), 'ma'])
                md_key = '_'.join([mmode, wavelet, str(N), 'md'])
                all_matlab_results[ma_key] = ma
                all_matlab_results[md_key] = md
finally:
    mlab.stop()

np.savez('dwt_matlabR2012a_result.npz', **all_matlab_results)
开发者ID:aaren,项目名称:pywt,代码行数:32,代码来源:generate_matlab_data.py

示例3: len

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import get_variable [as 别名]
        im_gt += [im]

    im_l = []
    if len(IMAGE_FILE)>0:
        assert(len(im_gt)==1)
        im_l = [np.array(Image.open(IMAGE_FILE)).astype(np.float32)]
    else: #down scale from ground truth using Matlab
        try:
            from pymatbridge import Matlab
            mlab = Matlab()
            mlab.start()
            for im in im_gt:
                mlab.set_variable('a', im)
                mlab.set_variable('s', 1.0/UP_SCALE)
                mlab.run_code('b=imresize(a, s);')
                im_l += [mlab.get_variable('b')]
            mlab.stop()
        except:
            print 'failed to load Matlab!'
            assert(0)
            #im_l = utils.imresize(im_gt, 1.0/UP_SCALE)

    #upscaling
    #sr = Bicubic()
    sr = SCN(MODEL_FILE)
    res_all = []
    for i in range(len(im_l)):
        t=time.time();
        im_h, im_h_y=sr.upscale(im_l[i], UP_SCALE)
        t=time.time()-t;
        print 'time elapsed:', t
开发者ID:CV-IP,项目名称:SCN_Matlab,代码行数:33,代码来源:main_test.py

示例4: get_ipython

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import get_variable [as 别名]
from IPython.display import clear_output
import matplotlib.pyplot as plt
import numpy as np
from numpy import sin, cos
from pymatbridge import Matlab
get_ipython().magic(u'matplotlib inline')
execfile('../../matplotlibrc.py')

# Run Matlab code and fetch relevant data
mlab = Matlab()
mlab.start()
results = mlab.run_code(open('fem1d.m').read())
K = mlab.get_variable('K')
U = mlab.get_variable('U')
nodeLocs = mlab.get_variable('nodeLocs')
mlab.stop()
clear_output()
print('K')
print(K)
print('U')
print(U)

x = nodeLocs[:,0]

xex = np.linspace(0, 1);
w = np.sqrt(2);
uex = (cos(w) - 1)*sin(w*xex)/(2.0*sin(w)) - 0.5*cos(w*xex) + 0.5

fig, ax = plt.subplots(figsize=(14, 10))
ax.plot(xex, uex, 'k-', label='Exact')
ax.plot(x, U, 'b-o', label='FEM')
开发者ID:selimb,项目名称:schoolstuff,代码行数:33,代码来源:problem2.py

示例5: print

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import get_variable [as 别名]
HSA_mfile_list = os.listdir('./Matlab_runcode/')
for files in HSA_mfile_list:
    shutil.move('./Matlab_runcode/' + files, HSA_dir)

# Delete unnecessary directories/files
os.remove('EEMD.zip')
os.remove('Matlab_runcode.zip')
os.rmdir('Matlab_runcode')
print('...Done.')

# Check the MATLAB version & replace the deprecated function with the new one.
mlab = Matlab()
print('* Checking your MATLAB version...')
mlab.start()
mlab.run_code('v = version;')
version = mlab.get_variable('v')
mlab.stop()
print('Your MATLAB version is: ' + version)
version = version.split('.')
if int(version[0]) >= 8:
    print('The function "getDefaultStream" in eemd.m is no longer be used ' +
          'in your MATLAB version.')
    print('* Replacing it with the function "getGlobalStream"...')
    with open(EEMD_dir + 'eemd.m', 'r', encoding='iso-8859-1') as infile:
            data = infile.read().replace('getDefaultStream', 'getGlobalStream')
    infile.close()
    with open(EEMD_dir + 'eemd2.m', 'w',encoding='iso-8859-1') as outfile:
        outfile.write(data)
    outfile.close()
    os.remove(EEMD_dir + 'eemd.m')
    os.rename(EEMD_dir + 'eemd2.m', EEMD_dir + 'eemd.m')
开发者ID:HHTpy,项目名称:HHTpywrapper,代码行数:33,代码来源:setup.py

示例6: Matlab

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import get_variable [as 别名]
#!/usr/bin/env python
# coding: UTF-8

from pymatbridge import Matlab
mlab = Matlab(executable='/Applications/MATLAB_R2014a.app/bin/matlab')

mlab.start()

results = mlab.run_code('a=1;')

var = mlab.get_variable('a')

print var
mlab.stop()
开发者ID:pengyuan,项目名称:markov2tensor,代码行数:16,代码来源:test.py

示例7: list

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import get_variable [as 别名]
        else:
            mlab.set_variable('wavelet', wavelet)
        if size_set == 'full':
            data_sizes = list(range(100, 101)) + \
                [100, 200, 500, 1000, 50000]
            Scales = (1,np.arange(1,3),np.arange(1,4),np.arange(1,5))
        else:
            data_sizes = (1000, 1000 + 1)
            Scales = (1,np.arange(1,3))
        mlab_code = ("psi = wavefun(wavelet,10)")
        res = mlab.run_code(mlab_code)
        if not res['success']:
            raise RuntimeError(
                "Matlab failed to execute the provided code. "
                "Check that the wavelet toolbox is installed.")
        psi = np.asarray(mlab.get_variable('psi'))
        psi_key = '_'.join([wavelet, 'psi'])
        all_matlab_results[psi_key] = psi
        for N in data_sizes:
            data = rstate.randn(N)
            mlab.set_variable('data', data)

            # Matlab result
            scale_count = 0
            for scales in Scales:
                scale_count += 1
                mlab.set_variable('scales', scales)
                mlab_code = ("coefs = cwt(data, scales, wavelet)")
                res = mlab.run_code(mlab_code)
                if not res['success']:
                    raise RuntimeError(
开发者ID:HenryZhou1002,项目名称:pywt,代码行数:33,代码来源:generate_matlab_data_cwt.py

示例8: MatlabBridgeDriver

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import get_variable [as 别名]
class MatlabBridgeDriver(MatlabDriver):
    """MATLAB driver which uses pymatbridge to do IPC with MATLAB."""

    # TODO(andrei): Consider reusing MATLAB instances across iterations by
    # using process-level locals, if something like that exists.

    def __init__(self):
        super().__init__()
        self.matlab = Matlab()

        # As of July 2016, there seems to be a bug which wrecks the data
        # dimensionality when feeding it to MATLAB, causing a matrix dimension
        # mismatch to happen.
        raise ValueError("MATLAB interop via pymatbridge doesn't work.")

    def start(self):
        """Starts MATLAB so that we may send commands to it.

        Blocks until MATLAB is started and a ZMQ connection to it is
        established.

        This is a very sensitive piece of code which can fail due to numerous
        misconfigurations. For instance, on ETH's Euler cluster, one must ensure
        that the proper modules are loaded before starting MATLAB, and that
        the MATLAB one is the first one loaded because of PATH concerns.

        Getting this to run might not be straightforward, and may require
        installing 'libzmq', 'pyzmq', and 'pymatbridge' from scratch on Euler.

        The process has not been tested on regular commodity hardware, such as
        AWS, but it should be much easier to run there due to the increased
        access to installing new packages directly via a package manager.

        TODO(andrei): Write guide for this.
        TODO(andrei): Maybe have a retry mechanic in case something fails.
        """
        super().start()
        self.matlab.start()
        self.matlab.run_code(r'''addpath(genpath('./matlab'))''')

    def _run_matlab_script(self, script, in_map):
        super()._run_matlab_script(script, in_map)

        start_ms = int(time.time() * 1000)

        logging.info("Have %d variables to set.", len(in_map))
        for vn, v in in_map.items():
            self.matlab.set_variable(vn, v)
        logging.info("Set all variables OK.")

        mlab_res = self.matlab.run_code('rungp_fn')
        print(mlab_res)

        if not mlab_res['success']:
            raise RuntimeError("Could not run MATLAB. Got error message: {0}"
                               .format(mlab_res['content']))

        result = self.matlab.get_variable('prob')
        print(result)

        # self.matlab.run_func('matlab/rungp_fn.m',
        #                      in_map['X'],
        #                      in_map['y'],
        #                      in_map['X_test'])

        # script_cmd = '{0} ; '.format(script)
        # self.matlab.run_code(script_cmd)
        end_ms = int(time.time() * 1000)
        time_ms = end_ms - start_ms
        logging.info("Ran MATLAB code using pymatbridge in %dms.", time_ms)

        # Dirty trick for testing
        # exit(-1)

        return result[:, 0]
开发者ID:AndreiBarsan,项目名称:crowd,代码行数:77,代码来源:bridge.py


注:本文中的pymatbridge.Matlab.get_variable方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。