Matlab: Importing functions in a class

2020-03-26 09:06发布

问题:

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.