Reading input m file in main m file

Hallo, I have a question about MATLAB I do not test in Matlab, and I would like to tell me if I have an input file (m file) containing some variables with their numbers, i.e. a = 5, b = 6, c = 7, and I want to use this m file in another program (the main file m), which uses these variables to calculate S = a + b + c. How can I read the input file in the main file? What commands should I use? What should be the first line? Suppose the input file is called INP and the main MAIN. Thank!

+3
source share
6 answers

This is usually not a good practice in MATLAB. The file containing the input variables will be a script in your example. Like your main file. MATLAB is not mistaken when running one script from another, as suggested by ScottieT812, but under certain circumstances strange errors may occur. (Run-time failure, problems with variable names in scripts)

The best option is to turn the script inputs into a function that returns the variables of interest

function [a,b c] = inputs
a = 5;
b = 6;
c = 7;

Then this function can be called in the main.m script.

% main.m
[a,b,c] = inputs;
s = a+b+c;
+6
source

For this kind of material (parameters that are easy to configure later) I almost always use structures:

function S = zark
    S.wheels = 24;
    S.mpg = 13.2;
    S.name = 'magic bus';
    S.transfer_fcn = @(x) x+7;
    S.K = [1 2; -2 1];

Then you can return a lot of data without having to do things like [a, b, c, d, e, f] = some_function;

- :

>> f = 'wheels';
>> S.(f)

ans =

    24
+3

"" m , "" m . , input.m, :

% File: inputs.m
a = 5;
b = 6;
c = 7;

main.m :

% File: main.m
inputs;
S = a + b + c;
+2

, , . , , . - . . "" "" Matlab.

+2

KennyMorton, MATLAB . m . , m , MATLAB . :

  • .m

, OPs, INP, . , ctfroot. MAIN :

eval(char(textread(fullfile(ctfroot, INP), '%s', 'whitespace', '');
0

script script, script . . :

%mydata.m
a = 1;
b = 2;


%mymain.m
mydata
whos
mymain

>> mymain

a 1x1 8 double
b 1x1 8 double

% foo.m
foo MYDATA

Whos >> foo

a 1x1 8 double
b 1x1 8 double

In general, it is preferable to use a MAT or other data file for this kind of thing.

0
source

Source: https://habr.com/ru/post/1698066/


All Articles