MATLAB: Is the output the function disregard the IF condition

functionif statement

Hi I've created a function,calcDist to calculate the distance travelled by a weight, W when put on springs, k1 and k2. If the distance travelled by the weight on the first spring, x is greater than the height difference of spring1(k1) and spring 2(k2), d then, the second equation should come in effect. The first equation only serves as a determiner of which case.
function x = calcDist(W,k1,k2,d)
x = W/k1 % equation 1
if x >= d
x = (W+2*k2*d)/(k1+2*k2) % equation 2
else
x = W/k1;
endif
endfunction
The function works for a single value of W.
>> calcDist(500,10^4,1.5*10^4,0.1)
ans = 0.050000
>>
>> calcDist(2000,10^4,1.5*10^4,0.1)
ans = 0.12500
>>
However since I need to plot a graph of x vs W for 0<W<3000N, I tried putting in multiple values at once in the command window
Try = calcDist(0:3000,10^4,1.5*10^4,0.1)
The output given was totally wrong. Somehow it skips the IF condition. I'm totally baffled by this situation. Any help and advice are greatly appreciated.

Best Answer

YOu cannot use if condition like that.....you better run a loop with your function calcDist as shown below and plot the required.
W = 0:3000 ;
k1 = 10^4 ;
k2 = 1.5*10^4 ;
d = 0.1 ;
x = zeros(size(W)) ;
for i = 1:length(W)
x(i) = calcDist(W(i),k1,k2,d)
end
plot(x,W)