Why does my function output a series of answers that I don't want and have tried my best to supress

1 view (last 30 days)
My code is as follows
function [T,Q]=osc_2
tspan = [0: pi/20: 2*pi];
qinit_1=[1;0];
qinit_2=[0;1];
[T,Q] = ode45(@osc,tspan,qinit_1);
phi_1=[Q((end), 1); Q((end), 2)];
[T,Q] = ode45(@osc,tspan,qinit_2);
phi_2=[Q((end), 1); Q((end), 2)];
eigenvalues=eig([phi_1,phi_2]);
Stability=eigenvalues(1,1)*eigenvalues(2,1)
end
with an accompanying second piece of code
function dqdt = osc(t,q)
dqdt = zeros(2,1);
a1=0;
a2=2;
a3=1;
dqdt(1) = q(2);
dqdt(2) = -a1*q(2)-q(1)*(a2+a3*cos(t));
end
When I run the first function, it returns the stability as I want it to, but it also outputs the following
ans =
0
0.1571
0.3142
0.4712
0.6283
0.7854
0.9425
1.0996
1.2566
1.4137
1.5708
1.7279
1.8850
2.0420
2.1991
2.3562
2.5133
2.6704
2.8274
2.9845
3.1416
3.2987
3.4558
3.6128
3.7699
3.9270
4.0841
4.2412
4.3982
4.5553
4.7124
4.8695
5.0265
5.1836
5.3407
5.4978
5.6549
5.8119
5.9690
6.1261
6.2832
Apologies for the length of the post, but is it possible to prevent the ans output from coming up? as far as I can tell it's simply giving the range of values used in tspan but I can't work out why it isn't supressed by the semicolon on that line.
I am very much new to MATLAB so simpler answers would be strongly prefered. I am also aware that there is most likely a different way of doing this as I only require the Q(end) values, however, this is the best I could do.

Accepted Answer

Mehmed Saad
Mehmed Saad on 8 Apr 2020
Because its your function output
[T,Q] =osc_2
will give you two output which you specified
when you call
osc_2
the output will be T stored in ans and also will display on cmd
on the other hand you cannot see Stability in your workspace
removing a semi colon will display it on cmd but will not pass it out of the function
when you call
osc_2;
value of T will be stored in ans but it wont get displayed on cmd
  4 Comments
Mehmed Saad
Mehmed Saad on 8 Apr 2020
% You can remove function from here though
tspan = [0: pi/20: 2*pi];
qinit_1=[1;0];
qinit_2=[0;1];
[T,Q] = ode45(@osc,tspan,qinit_1);
phi_1=[Q((end), 1); Q((end), 2)];
[T,Q] = ode45(@osc,tspan,qinit_2);
phi_2=[Q((end), 1); Q((end), 2)];
eigenvalues=eig([phi_1,phi_2]);
Stability=eigenvalues(1,1)*eigenvalues(2,1)
function dqdt = osc(t,q)
dqdt = zeros(2,1);
a1=0;
a2=2;
a3=1;
dqdt(1) = q(2);
dqdt(2) = -a1*q(2)-q(1)*(a2+a3*cos(t));
end

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!