Matlab calls a function in another file from one file

Part.I Introduction

This article introduces how to call the function in file A in script file B.

Insert image description here

Part.II Method

Purpose: Call the function in fileB.mA.m

By default, the two files are in one folder, otherwise you need to add the path

addpath('xxx')

There is only one function in the Chap.I A file

Just make the function name in the A.m file the same as the file name!

A.mdocument content

function sum = A(a,b)
sum=a+b;
end

B.mdocument content

%% main
A(1,2)

Run B directly to get

>> B

ans =

     3

There are multiple functions in the Chap.II A file

In this case, you need to add something to the header of the file. The specific demonstration is as follows:

A.mdocument content

%% Call ALL Function
function F = A
    F.add = @add;
    F.multiply = @multiply;
    F.mis = @mis;
end

%% Function body
function c = add(a,b)
c=a+b;
end

function c = multiply(a,b)
c=a*b;
end

function c = mis(a,b)
c=a-b;
end

B.mdocument content

%% main
A().add(1,2)			// 注意,一定要加括号!!!
A().multiply(2,3)
A().mis(4,3)

Run B directly to get

>> B

ans =

     3


ans =

     6


ans =

     1

Done!

Guess you like

Origin blog.csdn.net/Gou_Hailong/article/details/134698347