简体   繁体   中英

MATLAB Global Variable and Scripts

I have an m-file ParamStruct.m. Below are the contents of that file:

global Params
total_params = [];

Params.one   = 1;
Params.two   = 2;
Params.three = 3;

total_params = [total_params;Params];

Params.one   = 4;
Params.two   = 5;
Params.three = 6;

total_params = [total_params;Params];


for ii = length(total_params)
    
    Add_Param_Vals
end

Then I have another m-file which I use as a script called Add_Param_Values. The contents of that file are as follows:

global Params

disp("adding values: ")
Params.one + Params.two

The purpose of the two m-files is to 1.) define two Params structs in ParamStruct.m, then call Add_Param_Values from ParamStruct so that for each call, I can utilize the current Params struct as indexed by the for loop in ParamStruct. For example, when I run ParamStruct at the output I would like to see the following:

adding values:
ans =
     3

adding values:
ans =
     9

But instead I am seeing

adding values:
ans =
     9

So it seems like it is only utilizing the last element in the total_params variable and I dont know how to correct that. I do not want to modify anything in the Add_Param_Vals m-file as I am not the owner of it. Any ideas??

Sorry for the post. I was able to figure it out. Here is what I ended up doing:

global Params
total_params = [];

Params.one   = 1;
Params.two   = 2;
Params.three = 3;

total_params = [total_params;Params];

Params.one   = 4;
Params.two   = 5;
Params.three = 6;

total_params = [total_params;Params];


for ii = 1:length(total_params)
    Params = total_params(ii);
    Add_Param_Vals
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM