Matlab: Importing functions in a class

本小妞迷上赌 提交于 2019-12-19 10:37:27

问题


I have a class file in Matlab.

I created i directory structure using the package specifications.

+MyPkg
|--+F1
|--+F2
|--+F3
|  |--fun.m
|--myc.m

My class is myc and it is inserted in the package MyPkg.

A function fun is saved in subpackage F3 in the main one.

I want to use function fun in my class. How???


回答1:


You need to refer to fun as MyPkg.F3.fun everywhere. Unfortunately, full packages must be used explicitly everywhere in MATLAB (or, you must use import statements).




回答2:


The way you are describing using classes is the "old" way of doing it in Matlab. I don't know how it all works when you use the "old" way, but Class files make life way easier. I highly recommend them. This way you can put all of the functions for a class in one file. For example, you could create a file:

myclass.m

classdef myclass
  methods
    function out=add(a,b)
      out=a+b
    end
    function out=subtract(a,b)
      out=a-b
    end
  end
end

If you put myclass.m in the same folder as your m-file. Then you can access the class this way:

a=5;
b=3;
asdf=myclass;
c=asdf.add(a,b)
d=asdf.subtract(a,b)

There is a more extensive example at the following link:

http://www.mathworks.com/help/techdoc/matlab_oop/brhzttf.html

I hope that helps.



来源:https://stackoverflow.com/questions/10526765/matlab-importing-functions-in-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!