- did you declare the variables P,stiffness in your code?
- You cannot write zeros(1,t) where t(0:0.1:1) is not a positive integer.
- You also cannot write y(t), as in matlab indices are positive integers,you should start from y(1),in your code in the beginning itself it refers to y(0).
issues with if statement and plotting values
3 views (last 30 days)
Show older comments
I am a complete novice with the use of matlab and would like some advice.
I am trying to set up a list of numbers called 't' and a separate value named 'td'. I would then check whether each element within the list satisfies the condition t < td. If this condition is true, I would like to carryout the mathematical operation called 'op1' and if otherwise, carryout 'op2'. I would then like to plot values the operations against their corresponding values of 't'.
What I have tried so far is displayed below but does not work. Can someone point me in the correct direction and explain where I've been going wrong.
Omega = 183.3;
td = 0.5;
t = 0:0.1:1;
op1 = (P/stiffness)* ((1-cos(Omega*t)) + (sin(Omega*t)/(Omega*td)) - (t/td));
op2 = (P/stiffness)* ((1/(Omega*td)) * (sin(Omega*t) - sin(Omega*(t-td))) - cos(Omega*t));
y = zeros(1,t);
if t < td
y(t) = op1;
else
y(t) = op2;
end
plot(y,t) ;
0 Comments
Answers (3)
Luffy
on 23 Jun 2012
I did not exactly understand what you r trying to do,but here's my advice:-
Luffy
on 23 Jun 2012
I understand your code now,I took P & stiffness as 1 and wrote code,so you might add them to this code otherwise, I think this should help.
Omega = 183.3;
td = 0.5;
t = 0:0.1:1;
op1 = ((1-cos(Omega*t)) + (sin(Omega*t)/(Omega*td)) - (t/td)); % add P & stifness I put them to 1.
op2 = ((1/(Omega*td)) * (sin(Omega*t) - sin(Omega*(t-td))) - cos(Omega*t));
if t < td
y = op1;
else
y = op2;
end
plot(y,t) ;
plot(t,y) ; % this gave a better looking graph as in writing plot(t,y) plots graph with values of t on x-axis and y on y-axis.
Walter Roberson
on 15 Jul 2012
An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.
Your t is set to a row vector, t = 0:0.1:1, so when you compare to the scalar 0.5, some of t < 0.5 are true and some are false, and since not all the values are true, the "if" will be deemed to be false.
When you program an "if", mentally thing of there being an "all()" around the expression. If the result clearly will not work in context then you have programmed the wrong "if" and perhaps need to program a loop. Or, better yet, rewrite in terms of logical indexing.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!