"Function Keyword is invalid"

6 views (last 30 days)
Jordan Akins
Jordan Akins on 3 Sep 2019
Commented: Jordan Akins on 3 Sep 2019
Hi all,
I am attempting to write some code for a numerial analysis class. The problem was to crate a plot given an equation that calculates the displacement of a beam given an equation and some parameters.
H2P2.PNG
This is what I have.
clc; clear all; close all;
x = linspace(0,100,101);
u= -5/6*(vector(x,0,4)- vector(x,5,4))+15/6*vector(x,8,3)+75* vector(x,7,2)+57/6*x^3-238.25*x;
plot (x,u,'g--');
function vec = vector(x,a,n)
if x>a
vec = (x-a)^n;
elseif x<=a
vec = 0;
end
end
This code results in an error under the function. It tells me that I can't nest the function in an if statement. I don't see how I am doing that. Can someone please help me fix that error. Thank you!
  2 Comments
Walter Roberson
Walter Roberson on 3 Sep 2019
I agree that you do not appear to be nesting a function in an "if" statement. But I wonder if you are using R2016a or earlier, which did not permit functions inside of scripts?
Jordan Akins
Jordan Akins on 3 Sep 2019
That would be it. I am using 2012a. If I move to a later version it will probably work. Thanks for the info I would have never known.

Sign in to comment.

Answers (1)

Star Strider
Star Strider on 3 Sep 2019
The easiest solution is to use an anonymous function instead:
vectr = @(x,a,n) ((x-a).^n).*(x>a);
You can put that in your script wherever you like, providing it is before you first call it.
See the documentation section on Function Basics to understand where you can put them in a script. In general, it’s best to save them in their own files, then call them as necessary. Here, the equivalent function can be written as an anonymous function. (The value will be 0 where x<=a because of the ‘logical indexing’ convention this construction uses, so it is not necesssary to include that as a separate condition in this instance.)

Community Treasure Hunt

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

Start Hunting!