"Function Keyword is invalid"
4 次查看(过去 30 天)
显示 更早的评论
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.

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 个评论
Walter Roberson
2019-9-3
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?
回答(1 个)
Star Strider
2019-9-3
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.)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!