Piecewise functions using @ operator
13 views (last 30 days)
Show older comments
Hi Everyone, I'll try to make a long story short. I have a rocket flight simulator written by a classmate that I want to use to simulate how high my rocket will go given X, Y, and Z characteristics (knowns). In his model, he uses a constant thrust of 50 Newtons and the command is:
tf = 0.65; %seconds
F = @(t) 50;
t = (0:0.001:tf)
And then the code goes on to compute acceleration, velocity, and altitude. It works great for a constant value.
My engine is definitely NOT a constant thrust engine. I found a plot of thrust vs time, digitized it, and did a piecewise sum of least squares to find equations to model the thrust within a few percent. Now, since my thrust is not constant, how do I use the "@" operator. I know the equations, constants to go with them, and everything else - I just need the syntax on how to code it. I've tried something to this effect and it didn't work
F = @(t) m*t + b;
t = (0:0.001:tf)
if t >= 0.24
F = @(t) T_0*exp(-k*t)
t = (0.24:0.001:tf)
elseif t >= 0.34
F = @(t) T_02*exp(-k2*t)
t = (0.34:0.001:tf)
end
The problem is the script never enter the if statements and I'm simply getting linear thrust.
0 Comments
Answers (2)
Walter Roberson
on 15 Dec 2013
When you use "if" with a vector of values, the body of the "if" is only executed if all of the vector of values are non-zero. Since some of the values in the vector are true and some are false, the "if" (and likewise "elseif") are never considered true.
Also keep in mind that if there is a "t" which is not >= 0.24 (and so would reach the "elseif") then that t cannot possibly be >= 0.34. You should be thinking about reversing those two tests.
You should learn how to use logical indexing. And if you want to vectorize, there are tricks:
For example,
exp( -t .* ((t>=0.34) .* -k2 + (t>=0.24 & t<0.34) .* k) )
2 Comments
Walter Roberson
on 16 Dec 2013
F = @(t) ((t < 0.24) .* m*t + b) + ((t>=0.34) .* T_02 + (t>=0.24 & t<0.34) .* T_0) .* exp( -t .* ((t>=0.34) .* -k2 + (t>=0.24 & t<0.34) .* k) );
I do not recall ever before encountering anyone with "quite a bit of experience" with logical indexing who would test a vector with an "if" statement and be puzzled as to why the body of the "if" did not execute.
John Barber
on 16 Dec 2013
In addition to following Walter's advice about logical indexing, you'll want to learn about the differences between scripts, functions and anonymous functions, especially how variables are scoped in them. Another tip: with anonymous functions, it is difficult (but not impossible) to use conditional statements, and you should think about whether or not that is the best approach for you.
Here are some links to get you started:
0 Comments
See Also
Categories
Find more on Signal Generation and Preprocessing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!