Nested if in a for loop won't work
Mostrar comentarios más antiguos
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)
1 comentario
Antony Mohsen Kamal Masoud Kodsy
el 13 de Sept. de 2018
Respuesta aceptada
Más respuestas (1)
Steven Lord
el 12 de Sept. de 2018
2 votos
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.]
1 comentario
Antony Mohsen Kamal Masoud Kodsy
el 13 de Sept. de 2018
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!