Why is the output my function disregard the IF condition?
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
LuqmanF
am 12 Dez. 2018
Kommentiert: Steven Lord
am 13 Dez. 2018
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.
1 Kommentar
Steven Lord
am 13 Dez. 2018
KSSV has already given you an alternative. As for the reason why your if statement body was not executed, that's due to how if handles non-scalar expressions. 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.
The expression x >= d in your if statement contains only nonzero elements only if all the elements in the vector x are greater than the scalar d. The first element of the W vector you use to compute x is 0, thus the first element of x is also 0. The result of (0 >= 0.1) is false so the result of the expression has at least one zero element.
Instead of using a loop as KSSV did, you could use logical indexing. See this documentation page for more examples.
Akzeptierte Antwort
KSSV
am 12 Dez. 2018
Bearbeitet: KSSV
am 12 Dez. 2018
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)
0 Kommentare
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Animation finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!