How to call a function inside other function in a equation?

1 回表示 (過去 30 日間)
Danishtah Quamar
Danishtah Quamar 2022 年 1 月 25 日
コメント済み: Yongjian Feng 2022 年 1 月 25 日
I have one function function B=magnetic flux(x)
B=x(1)+x(2)+x(3);
end
Now I have to call B in other function function y=yield(x)
where y= x(1)*e^-B where B is magnetic flux
How to do it without writing the equation of B in second function

回答 (1 件)

Yongjian Feng
Yongjian Feng 2022 年 1 月 25 日
編集済み: Yongjian Feng 2022 年 1 月 25 日
It depends on whether you need to use B in anywhere else. If B is only used in your function yield, you can put it in the same m file, otherwise create a separate file for B.
  1. Case 1. Same m file. Call it yield.m
function y=yield(x)
B = magnetic_flux(x);
y= x(1)*e^(-B)
end
% internal function
function B=magnetic_flux(x)
B=x(1)+x(2)+x(3);
end
2. Case 2. Two m files. Put yield function in yield.m, and magnetic_flux function in magnetic_flux.m.
  2 件のコメント
Danishtah Quamar
Danishtah Quamar 2022 年 1 月 25 日
When I have 2 .m files. One for yield and one for magnetic flux. Then how to call magnetic_ flux.m files in yield.m files. Then what is the code for that.
Yongjian Feng
Yongjian Feng 2022 年 1 月 25 日
The simpliest way is to put both .m files in the same folder, then when access one file, the other file is also available. So two m files:
  1. yield.m
% you have one function in this file. Matlab will force you to name the
% file the same as the function name
function y=yield(x)
% magnetic_flux.m is in the same folder, so you can call it
B = magnetic_flux(x);
y= x(1)*e^(-B)
end
2. magnetic_flux.m (Please note the _ in the file name!)
% same here. One function in a m file. Matlab will force you to use the
% function name as the file name
function B=magnetic_flux(x)
B=x(1)+x(2)+x(3);
end

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by