Nested if in a for loop won't work
Afficher commentaires plus anciens
L=500;
a=300;
P=150;
EI=400;
n=20;
x=[0:L/n:L];
for ii=0:x
if x<a;
y=(P*x^2)*(3*a-x)/(6*EI)
elseif x>a;
x<L;
x=L;
y=(P*a^2)*(3*x-a)/(6*EI)
end
end
disp(y)
Réponse acceptée
Plus de réponses (1)
Steven Lord
le 12 Sep 2018
2 votes
The x variable is a vector.
I'm not certain what you expected your line of code "for ii=0:x" to do, but when you call colon (the : operator) with a nonscalar input (in this case your x variable is nonscalar) "MATLAB interprets j:i:k as j(1):i(1):k(1)." So this simplifies down to "for ii=0:0" or "for ii=0".
"if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
So your if statement body will only execute if ALL the elements of x are less than a. If that is not the case, the body of your elseif statement block will only execute if ALL the elements of x are greater than a. Neither of those are the case.
If I understand what you're trying to do correctly, you should use logical indexing (see the "Using Logicals in Array Indexing" section on this documentation page) or loop from 1 to the number of elements in x (which you can compute using the numel function) and inside the loop operate on each element of x in turn. [If this is for a homework assignment that says that you must use a for loop, use that approach. Otherwise I'd suggest using logical indexing.]
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!