Hướng dẫn python - matlab object

Main Content

This example shows how to create an object from a MATLAB® handle class and call its methods in Python®.

In your current folder, create a MATLAB handle class in a file named Triangle.m.

classdef Triangle < handle
    properties (SetAccess = private)
        Base = 0;
        Height = 0;
    end
    
    methods
        function TR = Triangle(b,h)
            TR.Base = b;
            TR.Height = h;
        end
        
        function a = area(TR)
            a = 0.5 .* TR.Base .* TR.Height;
        end
        
        function setBase(TR,b)
            TR.Base = b;
        end
        
        function setHeight(TR,h)
            TR.Height = h;
        end
    end
end

Start Python. Create a Triangle handle object and call its area method with the engine. Pass the handle object as the first positional argument.

import matlab.engine
eng = matlab.engine.start_matlab()
tr = eng.Triangle(5.0,3.0)
a = eng.area(tr)
print(a)

Copy tr to the MATLAB workspace. You can use eval to access the properties of a handle object from the workspace.

eng.workspace["wtr"] = tr
b = eng.eval("wtr.Base")
print(b)

Change the height with the setHeight method. If your MATLAB handle class defines get and set methods for properties, you can access properties without using the MATLAB workspace.

eng.setHeight(tr,8.0,nargout=0)
a = eng.area(tr)
print(a)

Note

Triangle class object tr, is a handle to the object, not a copy of the object. If you create tr in a function, it is only valid within the scope of the function.

See Also

matlab.engine.MatlabEngine | matlab.engine.FutureResult

  • Call MATLAB Functions from Python

Main Content

Nội dung chính

  • Accepted Answer
  • More Answers (0)
  • Categories
  • Community Treasure Hunt
  • Tổng quan
  • 1. Kiểm tra
  • 1.1 Bắt đầu Đồng hồ bấm giờ
  • 1.2 Phần trăm của tập dữ liệu
  • 1.3 Mảng di động (cell2mat)
  • 1.4 Mảng di động (num2cell)
  • 1.5 Chuỗi liên kết (strcat)
  • 1.6 Biểu đồ (histc)
  • 1.7 Độc đáo
  • 1.8 chồng chéo
  • Cân nhắc
  • BIÊN TẬP :

An opaque object has no properties and methods visible to MATLAB®. You can pass these objects to related functions that know how to work with them. Consult the documentation for the function that returned the opaque object to learn more about how to use it.

For example, this C++ code defines SessionHandle as typedef void*.

typedef void* SessionHandle;
SessionHandle getHandle(){
    // implement code here
};
void closeHandle(void * SessionHandle){};

After generating the MATLAB interface lib, call getHandle:

sessionHandle = clib.lib.getHandle
sessionHandle =
    SessionHandle is an opaque object.

The help for SessionHandle is:

clib.lib.SessionHandle    C++ opaque type.

You can pass the MATLAB sessionHandle variable to another function in the library:

clib.lib.closeHandle(sessionHandle)

Hi, I am plotting inversion results in a pcolor-plot, where I specify the transparency of each data point in dependance on the certainty of the model parameter. NaN is assigned to some model parameters, which appear white. Due to the resolution of the inversion grid, the boundary between the areas for which I have values and the NaN area appears very blocky.

In a plot that uses no transpareny, I can easily plot a white polygon with the "fill"-command which results in a sharp boundary. However, when I plot the white polygon with FaceALpha=1 above transparent elements, I can still see those elements below the polygon.

Here is an example that shows the effect:

clear all

close all

figure

polygon1=fill([1 3 3 1],[1 1 3 3],'r','FaceALpha',0.5);

hold on

polygon2=fill([2 4 4 2],[2 2 4 4],'b','FaceALpha',1);

polygon3=fill([2 4 4 2],[1 1 2 2],'w','FaceALpha',1);

xlim([0 5])

ylim([0 5])

The blue rectangle should cover the red one, why does the overlay appear purple then?

Accepted Answer

Edited: Jan on 24 Aug 2014

The code draws the polygons in the same z==0 plane. The transparency activates the OpenGL renderer. The renderer has to decide the order of patchs along the view direction, but this order is not well defined in OpenGL, because the renderer does not have any information about the order the objects have been defined inside Matlab - in opposite to the Painters renderer.

So try this:

figure

polygon1=fill3([1 3 3 1],[1 1 3 3],[1,1,1,1], 'r','FaceALpha',0.5);

hold on

polygon2=fill3([2 4 4 2],[2 2 4 4],[2,2,2,2], 'b','FaceALpha',1);

polygon3=fill3([2 4 4 2],[1 1 2 2],[3,3,3,3], 'w','FaceALpha',1);

xlim([0 5])

ylim([0 5])

pause(1)

view(2)

More Answers (0)

See Also

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.


Tổng quan

Gần đây trong công việc của mình, tôi đã viết lại các thuật toán được phát triển trong MatLab sang Python , một số hàm không đơn giản để thích nghi, đặc biệt là các hàm mảng được gọi là Mảng di động .

Nội dung chính

  • Tổng quan
  • 1. Kiểm tra
  • 1.1 Bắt đầu Đồng hồ bấm giờ
  • 1.2 Phần trăm của tập dữ liệu
  • 1.3 Mảng di động (cell2mat)
  • 1.4 Mảng di động (num2cell)
  • 1.5 Chuỗi liên kết (strcat)
  • 1.6 Biểu đồ (histc)
  • 1.7 Độc đáo
  • 1.8 chồng chéo
  • Cân nhắc
  • BIÊN TẬP :

Nội dung chính

  • Tổng quan
  • 1. Kiểm tra
  • 1.1 Bắt đầu Đồng hồ bấm giờ
  • 1.2 Phần trăm của tập dữ liệu
  • 1.3 Mảng di động (cell2mat)
  • 1.4 Mảng di động (num2cell)
  • 1.5 Chuỗi liên kết (strcat)
  • 1.6 Biểu đồ (histc)
  • 1.7 Độc đáo
  • 1.8 chồng chéo
  • Cân nhắc
  • BIÊN TẬP :

Nội dung chính

  • Tổng quan
  • 1. Kiểm tra
  • 1.1 Bắt đầu Đồng hồ bấm giờ
  • 1.2 Phần trăm của tập dữ liệu
  • 1.3 Mảng di động (cell2mat)
  • 1.4 Mảng di động (num2cell)
  • 1.5 Chuỗi liên kết (strcat)
  • 1.6 Biểu đồ (histc)
  • 1.7 Độc đáo
  • 1.8 chồng chéo
  • Cân nhắc
  • BIÊN TẬP :

MatLab có API nơi bạn có thể gọi các hàm MatLab thông qua Python. Tuy nhiên, ý tưởng không phải là sử dụng MatLab, nhưng cùng một thuật toán hoạt động theo cùng một cách chỉ sử dụng Python và NumPy và GNU Octave cũng có API tương tự như MatLab.

Để duy trì khả năng tương thích, tôi đã tạo các hàm có cùng tên được sử dụng trong MatLab được gói gọn trong một lớp có tên là Precision .

1. Kiểm tra

Tạo bản sao kho lưu trữ và làm theo các hướng dẫn trong tệp README:

  • https://github.com/edersoncorbari/mat2py

Dưới đây tôi sẽ chỉ ra một số ví dụ, chúng được chứa trong các bài kiểm tra đơn vị.

1.1 Bắt đầu Đồng hồ bấm giờ

Đo lường thời gian dành cho chế biến.

from precision import Precision

p = Precision()
p.tic()
for i in range(0, 1000): print(i)
p.toc()

Đầu ra sẽ trông giống như thế này:

: > Elapsed time is 0:0:2 secounds.

1.2 Phần trăm của tập dữ liệu

Điều này được sử dụng để có được một phần trăm. Trong ví dụ dưới đây, chúng tôi đang tạo ra một phạm vi ngày thứ tự bằng cách cắt 5% từ bên trái và 5% từ bên phải.

from datetime import datetime
from precision import Precision

p = Precision()
d = [i for i in p.dtrange(datetime(2018, 6, 12), 
                          datetime(2059, 12, 12), 
                          {'days':1, 'hours':2})]
x = [p.datenum(i.date()) for i in d]

x1 = p.prctile(x, 5)
x2 = p.prctile(x, 95)
r = (x2 - x1)

Đầu ra sẽ trông giống như thế này:

5% lower: 737980.1
5% higher: 751621.9
delta: 13641.800000000047

1.3 Mảng di động (cell2mat)

Điều này chuyển đổi một mảng ô thành một mảng thông thường của kiểu dữ liệu cơ bản.

from precision import Precision

p = Precision()
p.cell2mat([[1, 2], [3, 4]])
p.cell2mat('1 2; 3 4')

Đầu ra sẽ trông giống như thế này:

matrix([[1, 2],
        [3, 4]])

1.4 Mảng di động (num2cell)

Chuyển đổi mảng thành mảng ô với các ô có kích thước phù hợp.

import numpy
from precision import Precision

p = Precision()
x = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], numpy.int64)
p.num2cell(x)

Đầu ra sẽ trông giống như thế này:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

1.5 Chuỗi liên kết (strcat)

Điều này nối chuỗi theo chiều ngang bằng cách sử dụng strcat.

import pandas
from precision import Precision

p = Precision()
df = pandas.DataFrame(data={'A': [1, 2], 'B': [3, 4]}, dtype=numpy.int8)
p.strcat(df, 'B')

Đầu ra sẽ trông giống như thế này:

['3', '4']

1.6 Biểu đồ (histc)

Điều này đếm số lượng giá trị trong x nằm trong mỗi phạm vi bin được chỉ định. Đầu vào, binranges, xác định điểm cuối cho mỗi thùng. Đầu ra, bincounts, chứa số phần tử từ x trong mỗi thùng.

import numpy 
from precision import Precision

p = Precision()
v = numpy.array([[1.5, 2.0, 3], [4, 5.9, 6]], numpy.int64)
p.histc(v, numpy.amax(v) + 1)

Đầu ra sẽ trông giống như thế này:

(array([1, 1, 1, 0, 1, 1, 1]), array([1., 1.71428571, 2.42857143, 
       3.14285714, 3.85714286, 4.57142857, 5.28571429, 6.]))

1.7 Độc đáo

Tìm kiếm các giá trị duy nhất trong một mảng và trả về các chỉ mục, nghịch đảo và đếm.

import numpy 
from precision import Precision

p = Precision()
x = [0, 1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 7]
p.unique(numpy.array([x]))

Đầu ra sẽ trông giống như thế này:

array([[array([0, 1, 2, 3, 4, 5, 6, 7]),
        array([[ 0,  1,  3,  4,  5,  7,  9, 10]]),
        array([0, 1, 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 7]),
        array([1, 2, 1, 1, 2, 2, 1, 3])]], dtype=object)

1.8 chồng chéo

Tìm kiếm các lớp phủ giữa hai mảng trả về chỉ mục.

import numpy 
from precision import Precision

p = Precision()
x, y = p.overlap2d(numpy.array(['A','B','B','C']), 
                   numpy.array(['C','A','B','C','D']))

Đầu ra sẽ trông giống như thế này:

(array([0, 1, 2, 3]), array([1, 2, 0, 3]))

Cân nhắc

Có những chức năng không chính xác là MatLab nhưng sẽ đóng vai trò hỗ trợ, tôi hy vọng nó có thể giúp được ai đó. Có một bài viết thú vị trong NumPy cho người dùng đang chuyển từ MatLab sang Python.

  • NumPy cho MATLAB © Người dùng

0 hữu ích 0 bình luận 12k xem chia sẻ

Tôi đã điều chỉnh perl.mthành python.mvà đính kèm điều này để tham khảo cho những người khác, nhưng dường như tôi không thể nhận bất kỳ đầu ra nào từ các tập lệnh Python để được trả về biến MATLAB :(

Đây là M-file của tôi; lưu ý rằng tôi trỏ trực tiếp đến thư mục Python C:\python27_64, trong mã của tôi, và điều này sẽ thay đổi trên hệ thống của bạn.

function [result status] = python(varargin)
cmdString = '';
for i = 1:nargin
    thisArg = varargin{i};
    if isempty(thisArg) || ~ischar(thisArg)
        error('MATLAB:python:InputsMustBeStrings', 'All input arguments must be valid strings.');
    end
    if i==1
        if exist(thisArg, 'file')==2
            if isempty(dir(thisArg))
                thisArg = which(thisArg);
            end
        else
            error('MATLAB:python:FileNotFound', 'Unable to find Python file: %s', thisArg);
        end
    end
  if any(thisArg == ' ')
    thisArg = ['"', thisArg, '"'];
  end
  cmdString = [cmdString, ' ', thisArg];
end
errTxtNoPython = 'Unable to find Python executable.';
if isempty(cmdString)
  error('MATLAB:python:NoPythonCommand', 'No python command specified');
elseif ispc
  pythonCmd = 'C:\python27_64';
  cmdString = ['python' cmdString];  
  pythonCmd = ['set PATH=',pythonCmd, ';%PATH%&' cmdString];
  [status, result] = dos(pythonCmd)
else
  [status ignore] = unix('which python'); %#ok
  if (status == 0)
    cmdString = ['python', cmdString];
    [status, result] = unix(cmdString);
  else
    error('MATLAB:python:NoExecutable', errTxtNoPython);
  end
end
if nargout < 2 && status~=0
  error('MATLAB:python:ExecutionError', ...
        'System error: %sCommand executed: %s', result, cmdString);
end

BIÊN TẬP :

Giải quyết vấn đề của tôi, perl.m ban đầu trỏ đến một cài đặt Perl trong thư mục MATLAB bằng cách cập nhật PATH sau đó gọi Perl. Hàm trên trỏ đến cài đặt Python của tôi. Khi tôi gọi function.pytệp của mình , nó nằm trong một thư mục khác và được gọi là các tệp khác trong thư mục đó. Những thứ này không được phản ánh trong PATH và tôi đã phải easy_install các tệp Python của mình vào bản phân phối Python của mình.

4 hữu ích 0 bình luận chia sẻ