How to create variable names and then declare them as global in a function
2 次查看(过去 30 天)
显示 更早的评论
I have multiple global varibles that come in triplets of the form:
f1, f1_max, f1_min
f2, f2_max, f2_min
f3, f3_max, f3_min
... and so on ...
I am trying to create a function that only takes in the input fx and will output the four values that are determined by a series of calculations using the corresponding 3 global values. Because I am inputting only one value, fx, I need a way to declare fx_max and fx_min as global variables. In other words, I need first to assemble those variables and then somehow declare them as global. I thought about using the eval function like this:
function [avg_year, total, start_date, end_date] = avg_func(name_of_func)
global eval(append(string(name_of_func), '_max')) eval(append(string(name_of_func), '_min'))
% rest of func
end
This however fails and returns the following message:
Error: File: avg_func.m Line: 2 Column: 27
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise,
check for mismatched delimiters.
Does anyone else have a alternative method?
2 个评论
Stephen23
2021-9-29
编辑:Stephen23
2021-9-29
"Does anyone else have a alternative method?"
Using global variables is a sign that most likely you are doing something wrong.
Numbering variables like that is a sign that most likely you are doing something wrong.
Is there any good reason why you cannot use basic arrays+indexing, just like MATLAB was design for?
回答(1 个)
Steven Lord
2021-9-29
Consider using a struct array. This can encapsulate the related data into one variable that can be easily passed into functions. Functions can have the same signature (just accept the struct as input) but can use any or all of the fields in the struct as they choose. Note that even though s1 and s2 in the example below contain different data, the same displayValues function can handle each of them.
s1 = struct('name', 'f', 'f', 42, 'f1', -99, 'f1x', 1);
s2 = struct('name', 'z', 'z', 88, 'z1', 5, 'z1x', -12345);
displayValues(s1)
displayValues(s2)
function displayValues(f)
N = f.name;
fprintf('The struct variable contains %s = %d, %s = %d, and %s = %d.\n', ...
N, f.(N), N + "1", f.(N + "1"), N + "1x", f.(N + "1x"));
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!