how to put a function with conditions in a parent function
Show older comments
Hello everyone ^^
Objective : I want to put a function (F1) 'with conditions' in another one (F2) ==> F2 = fct(F1)
I have implemented the attached code, which I can't get to work! knowing that the function (F1) works fine by itself,
error message : 'Not enough input arguments in F2' I have tried many things but I can't understand the error, if anyone can help me out of this problem, I would be very grateful,
thank you in advance!
function f = F2(R,t)
t = [0:0.1:48]';
V = 1.408 + 1;
K1= 0.034701409774022;
r = F1(t);
f = (1/V).*(1-exp(-((t.*V.*K1)+((t.*V)./(R.*r)))));
function r = F1(t)
p1 = 2.585*10^(-06);
p2 = -9.23*10^(-05);
p3 = 0.001032;
p4 = -0.002989;
p5 = 0.7562;
mask = t <= 27;
r(mask) = p1.*t(mask).^4 + p2.*t(mask).^3 + p3.*t(mask).^2 + p4.*t(mask) + p5;
mask = t > 27;
r(mask) = 1;
end
end
4 Comments
Looks to be in the calling/use of F2, the functions themselves appear to be OK.
Although from a sytlistic standpoint you could save a little code in F1 by writing
r=ones(size(t)); % preallocate; set to 1
mask= (t<=27); % set the range to use correlation results
r(mask) = p1*t(mask).^4 + p2*t(mask).^3 + p3*t(mask).^2 + p4*t(mask) + p5;
that saves one logical operation by setting all to 1 first, then fixing up those not to be 1. (I also introduced a set of parentheses that make, for me, the logical vector definition easier to read although they're not needed for syntax.)
One other shorthand using MATLAB builtin functions would be
function r = F1(t)
r=ones(size(t)); % preallocate; set to 1
p = [2.585e-6, -9.23e-5, 0.001032, -0.002989, 0.7562]; % put poly coeff in array
mask= (t<=27); % set the range to use correlation results
r(mask) = polyval(p,t(mask)); % let polyval() do the hard work to evaluate
end
Walter Roberson
on 6 Apr 2021
How are you invoking F2 ?
function f = F2(R,t)
t = [0:0.1:48]';
Why are you overwriting the t that the user passed into the function?
dpb
on 7 Apr 2021
Good catch on the use of t, Walter. I overlooked it, indeed.
Fatma Hadj salem
on 8 Apr 2021
Answers (0)
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!