There are multiple approaches passing constants to MATLAB functions
Defining variables as global is a simple solution.
Using global makes the variable "visible" to all functions and scripts. The downside of using global, is that it's not extendable, and prevents code reuse.
From academic software engineering perspective, you shouldn't use global variables at all. Assuming your code is used for solving a specific problem and not going to be extended or reused, using global is permitted.
Using global:
Declare the constants as global before initialization:
global K g
K=0.5; % minor loss coefficient (square edged)
g=9.8; % gravity in m/s2
Declare the variables as global in any function that uses them:
function v1=velocity1(f)
global K g
v1= sqrt((2*g*h)/(1+(f*(L./D))+K));
end
Using nested functions:
Instead of using global, you can use "nested functions" approach - an inner function can access the variables of an outer function.
Define your main script as a function, and velocity1 as an inner function:
function main()
%main is the outer function, and velocity1 is an inner function
K=0.5; % minor loss coefficient (square edged)
g=9.8; % gravity in m/s2
h=1;L=3;D=4;
f1= 2; %(value obtained from external function)
v1=velocity1(f1);
%Inner function:
function v1=velocity1(f)
v1= sqrt((2*g*h)/(1+(f*(L./D))+K));
end
end
Passing a struct of parameters to the function:
A common solution is MATLAB is passing a struct with constant parameters to all functions that uses them:
param.K=0.5; % minor loss coefficient (square edged)
param.g=9.8; % gravity in m/s2
param.h=1;param.L=3;param.D=4;
f1= 2; %(value obtained from external function)
v1=velocity1(f1, param);
function v1=velocity1(f, par)
K = par.K;
g = par.g;
h=par.h;L=par.L;D=par.D;
v1= sqrt((2*g*h)/(1+(f*(L./D))+K));
end
There are other approaches, but I can't list them all...