Error message that relates to output of user-defined function

1 view (last 30 days)
Im trying to create a function that measures the displacement of a beam however I keep getting the same error message fo my code.
function y= displacement(x,a,W,E,I,L)
x=linspace(0,L)
if x<=a & x>=0
y= -((W*x.^2)/(6*E*I))*((3*a)-x)
else if x>=a & x<=L
y = -((W*a.^2)/(6*E*I))*((3*x)-a)
end
end
I=0.163
L=10
a=3
W=1000
y = displacement(x,a,W,E,I,L)
Error in displacement (line 2) x=linspace(0,L)
Output argument "y" (and maybe others) not assigned during call to "displacement".
And I'm really not sure why this occurs

Accepted Answer

Star Strider
Star Strider on 4 Feb 2016
One problem I see is that ‘x’ is an input argument to your function, then you overwrite it with a 100-element vector:
x=linspace(0,L)
The problem is that logical comparison statements are not straightforward with vectors.
I’m not certain what you want to do with your code. I will leave this to you to sort.
  2 Comments
Star Strider
Star Strider on 4 Feb 2016
I would create your function as an anonymous function, incorporating the logic to choose the appropriate values of ‘x’ by creating and multiplying the subsections of your calculation by appropriate logical vectors, so the result is correct.
This works (although I had to guess at a value for ‘E’):
displacement = @(x,a,W,E,I,L) [(-((W*x.^2)./(6*E*I)).*((3*a)-x)).*(x<=a & x>=0) + (-((W*a.^2)./(6*E*I))*((3*x)-a)).*(x>=a & x<=L)];
I=0.163;
L=10;
a=3;
W=1000;
E = 10; % <— MISSING ARGUMENT
x=linspace(0,L);
y = displacement(x,a,W,E,I,L);
figure(1)
plot(x, y)
grid

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!