How to insert code segments from another MATLAB file?

5 ビュー (過去 30 日間)
Camila Perico
Camila Perico 2018 年 12 月 18 日
コメント済み: Camila Perico 2018 年 12 月 18 日
Hello!
Could anyone tell me how can I "import" MATLAB code segments into another code?
I mean, I have some parameters in a file and I want to embed it in a function, for example, a data input.
input.dat:
x=1;
y=2; % or something more complex than that
main code:
function result = func(M)
% I want to insert my input here
M=M*x;
result = M+y;
end
Thanks for your help!
  1 件のコメント
per isakson
per isakson 2018 年 12 月 18 日
編集済み: per isakson 2018 年 12 月 18 日
Are you sure you want to do that? I cannot justify this construct.
Rename input.dat to my_input.m, move it to a folder that's in the search path and add the line
my_input
to your function.

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

採用された回答

Gareth
Gareth 2018 年 12 月 18 日
There usually are 3 ways that I have seen people do this.
  • in your func.m add a comment with a special TAG (e.g. %#mycode), then replace the TAG with the code you want. This can be done with simple fileread(filename). This will work for *.m or any other text files
  • in your func.m call a script as per is suggesting (this could be empty or with data) so your func.m will always run, it may error out if the script file is not generated properly
  • in your func.m if you are only loading variables you could always load a mat file
Hope this helps
  1 件のコメント
Camila Perico
Camila Perico 2018 年 12 月 18 日
Thank tou per isakson and GT, you helped me a lot. All sugestions worked well.

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by