Fixing a plot with error message: "Function behaves unexpectedly on array inputs...properly vectorize your function"

I am trying to plot my function "massactcup_frustrumwt" for a range of different values of "t" but every time I try to plot it, though it plots properly, I get an error message: "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. "
Can someone please explain to me what this error message means? What does it mean to properly vectorize a function? Also, how should I change my function so that it plots without producing this error message? I want to be able to fix this problem in the future. My function is below:
function [y] = massactcup_frustrumwt (h, rob, rot, t)
rib=rob-t;
rit=rot-t;
A=(rob^2+2*rob*rot+3*rot^2)-(rib^2+2*rib*rit+3*rit^2);
B=(rob^2+rob*rot+rot^2)-(rib^2+rib*rit+rit^2);
COGz=h*A/(4*B);
y=COGz;
end
% Units: everything is in cm. y and y0 are expressed in cm
Thank you,
Jordan

1 Comment

'I get an error message: "Function behaves unexpectedly on array inputs...'
Note that you actually get a warning, not an error. Errors means that the code stops being evaluated, and are shown in red.

Sign in to comment.

 Accepted Answer

"Can someone please explain to me what this error message means? "
It means that your function returns a differently-sized output than its input. This often happens when beginners use linear algebra operators (i.e. "matrix operators") when they should have actually used element-wise operators (i.e. "array operators"):
"What does it mean to properly vectorize a function?"
Search the internet for "MATLAB vectorize" using [a major internet search engine], and this is the very first result returned:
Vectorization is useful because it can make some code look very similar to its mathematical equivalent, it can be very compact, and can be very efficient to run. Not all code can be vectorized, nor should be vectorized, and it may also be slower if it generates large intermediate variables.
"Also, how should I change my function so that it plots without producing this error message?"
You will need to change all of the matrix operators for array operators, e.g.
* to .*
^ to .^
/ to ./
etc.
"I want to be able to fix this problem in the future."
That is a very good aim, because using MATLAB without knowing the difference between matrix operators and array operators will just produce nonsense and you won't know why.

1 Comment

Thank you Steven for helping me to fix the problem in my function and referencing me to additional resources to help myself in the future.

Sign in to comment.

More Answers (0)

Products

Release

R2018b

Tags

Community Treasure Hunt

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

Start Hunting!