필터 지우기
필터 지우기

How does the following two codes differ? both are working, but they are yielding different answers

조회 수: 1 (최근 30일)
Hello,
Could you explain for me why I'm not getting the same answer from the following two codes??
function whatswrong(x)
x1= linspace(0,x);
n=length(x1);
uy = -5/6.*(sing2(x1,0,4)-sing2(x1,5,4))...
+ 15/6.*sing2(x1,8,3) + 75*sing2(x1,7,2)...
+ 57/6.*x1^3 - 238.25.*x1;
plot(x1,uy,'--')
xlabel('x1')
ylabel('uy'),
title('displacement versus distance')
function check = sing2(x1,a,n)
if x1 > a
check = (x1 - a).^n;
else
check=0;
end
------------------------------------------------------------------------------------------------------
function beam2(x)
x1= linspace(0,x);
n=length(x1);
for i=1:n
uy(i) = -5/6.*(sing(x1(i),0,4)-sing(x1(i),5,4));
uy(i) = uy(i) + 15/6.*sing(x1(i),8,3) + 75*sing(x1(i),7,2);
uy(i) = uy(i) + 57/6.*x1(i)^3 - 238.25.*x1(i);
end
plot(x1,uy)
function check = sing(x1,a,n)
if x1 > a
check = (x1 - a).^n;
else
check=0;
end
many many thanks,

채택된 답변

Roger Stafford
Roger Stafford 2015년 3월 15일
In the functions 'sing' and 'sing2' you have "if x1 > a". If x1 is a many-element vector, this only comes true what all elements are greater than a. Since you are presenting 'sing' with a scalar x1 one at a time and 'sing2' with a vector, you will get different results from them. You need to rewrite 'sing2' if you want the vectorized 'whatswrong' to work properly.
Also in 'whatswrong' you have written x1^3 where x1 is a vector and that should give you an error message, not a result. I assume you didn't actually run it that way if you got a result.
  댓글 수: 3
Roger Stafford
Roger Stafford 2015년 3월 15일
It can be written in vectorized form as:
function check = sing2(x1,a,n)
check = (x1>a).*(x1-a).^n;
end
If you prefer a for-loop, it could be:
function check = sing2(x1,a,n)
check = zeros(size(x1));
for k = 1:length(x1);
if x1(k) > a
check(k) = (x1(k)-a)^n;
end
end
end
Note that in this second method the condition after the 'if' gets applied one at a time and therefore gives you the same result as obtained with your use of 'sing'.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by