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)

 채택된 답변

Stephan
Stephan 2018년 9월 12일
편집: Stephan 2018년 9월 12일

1 개 추천

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

추가 답변 (1개)

Steven Lord
Steven Lord 2018년 9월 12일

2 개 추천

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.]

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by