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)

 Akzeptierte Antwort

Stephan
Stephan am 12 Sep. 2018
Bearbeitet: Stephan am 12 Sep. 2018

1 Stimme

Hi,
read how matlab works, in the answer above and the given links. Try this:
L=500;
a=300;
P=150;
EI=400;
n=20;
x=0:L/n:L;
y=zeros(1,length(x));
for ii=1:length(x)
if x(ii)<a;
y(ii)=(P*x(ii)^2)*(3*a-x(ii))/(6*EI);
elseif x(ii)>a;
y(ii)=(P*a^2)*(3*x(ii)-a)/(6*EI);
end
end
disp(y)
Best regards
Stephan

Weitere Antworten (1)

Steven Lord
Steven Lord am 12 Sep. 2018

2 Stimmen

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".
Now when you use if with a nonscalar condition, how does it behave? From the documentation:
"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.]

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by