Why my function is not vectorized

2 views (last 30 days)
This is my code:
dv = [1 5 10 20 50];
vc = sqrt(0.8*200*2*365*24*3600)/1000;
figure
for i = 1:5
dvc = dv(i);
f = @(c) exp(-1*dvc/c)-((c/vc)^2)*(1-exp(-1*dvc/c));
fplot(f,[10 1000])
hold on
end
I was told by the fplot that it has array input,
Warning: Function behaves unexpectedly on array inputs. To improve performance,
properly vectorize your function to return an output with the same size and shape as
the input arguments.
> In matlab.graphics.function.FunctionLine>getFunction
In matlab.graphics.function/FunctionLine/updateFunction
In matlab.graphics.function.FunctionLine.set.Function_I
In matlab.graphics.function.FunctionLine.set.Function
In matlab.graphics.function/FunctionLine
In fplot>singleFplot (line 245)
In fplot>@(f)singleFplot(cax,{f},limits,extraOpts,args) (line 200)
In fplot>vectorizeFplot (line 200)
In fplot (line 166)
In AE435HW2 (line 16)
but none of the input is an array though? Does it mean my function handle c?

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 25 Jan 2023
Edited: Dyuman Joshi on 25 Jan 2023
dv = [1 5 10 20 50];
vc = sqrt(0.8*200*2*365*24*3600)/1000;
figure
for i = 1:5
dvc = dv(i);
%vectorizing the function handle
f = @(c) exp(-1.*dvc./c)-((c./vc).^2).*(1-exp(-1.*dvc./c));
fplot(f,[10 1000])
hold on
end

More Answers (1)

Nikhilesh
Nikhilesh on 25 Jan 2023
You can fix this issue by vectorizing the function, so that it can handle arrays of inputs and produces arrays of outputs. One way to do this is to use element-wise operations on the variables in the function, like this:
f = @(c) exp(-1*dv(i)./c)-((c/vc).^2).*(1-exp(-1*dv(i)./c));

Categories

Find more on MATLAB in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!