當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。