Why my function is not vectorized

2 Ansichten (letzte 30 Tage)
JingChong Ning
JingChong Ning am 25 Jan. 2023
Beantwortet: Nikhilesh am 25 Jan. 2023
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?

Akzeptierte Antwort

Dyuman Joshi
Dyuman Joshi am 25 Jan. 2023
Bearbeitet: Dyuman Joshi am 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

Weitere Antworten (1)

Nikhilesh
Nikhilesh am 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));

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by