Your first part is wrong, please tell me how can you compare x with d without having x defined first?
Please test your functions first so we can help you better, the statement
is also wrong, it should be something similar to
but that condition is irrelevant, it should only be
because it's the opposite condition from the if, it takes all the values that the if doesn't "catch".
Your second expression should be
x=(W + 2*d*k2)/(k1 + 2*k2)
I made the plotting but I won't post the code because you must do your own homework and learn with your own mistakes.
Edit: ok here' the code, I'm just posting it because Big Meech shown that he's working on the homework and the use of logical indexing is the way to go (Matt Fig sugestion), the following code works just fine but it's slower than the one using logical indexing.
function x=spring(W,k1,k2,d)
if ((W/k1)<d)
x= W/k1;
else
x=(W + 2*d*k2)/(k1 + 2*k2);
end
Script for the plot, this is not one optimized version, there's no pre-allocation of the x and the plot is called too many times (each time creating a new object thus wasting time and memory)
clf
hold on
st=5;
for W=0+st:st:3000-st;
x=spring(W,k1,k2,d);
plot(W,x)
end
extra text and lines
line([0 k1*d],[d d],'linestyle','--','color',[1 0 0])
line([k1*d k1*d],[0 d],'linestyle','--','color',[1 0 0])
text(0,d,'d')
text(k1*d,0,'k_1*d')
text(k1*d/2,d/2,'x=W/k_1')
text(k1*d+k1*d/6,d+d/6,'x=(W + 2*d*k_2)/(k_1 + 2*k_2)')
Just for fun I tested both ways to do it, logical indexing got also the pre-allocation of x memory space.
k1 = 10000;
k2 = 15000;
d = 0.1;
W = 500;
st=0.1;
Time required for the plot to be done with logical indexing: 0.029902 seconds.
Time required for the plot to be done with if and else: 23.764888 seconds.
It's a big difference!
Last Edit
Here's the version with logic indexing
function x=spring2(W,k1,k2,d)
x=0*W;
x((W/k1)<d)= W(W<k1*d)/k1;
x((W/k1)>=d)=(W(W>=k1*d) + 2*d*k2)/(k1 + 2*k2);
end
Script that calls the function (don't put it in the same file as the function!!!)
k1 = 10000;
k2 = 15000;
d = 0.1;
st=0.1;
x=zeros(1,3000/st-2);
W=0+st:st:3000-st;
x(1:numel(W))=spring2(W,k1,k2,d);
plot(W,x)
If you want to compare the time it takes to execute use the tic and toc functions, the version with pre-allocating of memory and logic indexing is the best way to do it.
Best Answer