Why my function is not vectorized

조회 수: 3 (최근 30일)
JingChong Ning
JingChong Ning 2023년 1월 25일
답변: Nikhilesh 2023년 1월 25일
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?

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 1월 25일
편집: Dyuman Joshi 2023년 1월 25일
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

추가 답변 (1개)

Nikhilesh
Nikhilesh 2023년 1월 25일
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));

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by