# I'm not getting table

1 view (last 30 days)
Abrar Kondkar on 18 Sep 2019
Answered: Star Strider on 18 Sep 2019
%Step 1:
% define function
function Assignment3part3()% Function will be in loop
function result = f_example(x,t)
%rhs functions in ODEs
result (1) = -15.068 * x(1) + 3.623*x(2) + 1; %Rate 1
result (2) = 6.973 * x(1) - 13.61*x(2) + 3.371; %Rate 2
end
function [tstore,xstore] = solve_euler (f, t0, x0, deltat, jstep, mtime)
% solutions of systems of ODEs by eluer stepping
% f (function f(x,t) that supplies right-hand sides of ODEs
% t0 initial time
% x0 initial value of vector x
% deltat time step
% jstep number of time steps between stored results
% mtime number of stored rsults after time t0
% tstore(m+1) = time at stored step m
% xstore(m+1,:)= solution vector x at stored step m
% Step 2:
% initial values
t= t0;
x= x0;
tstore( 1) =t;
xstore(:,1)=x';
% Step 3:
%time stepping
for m = 1 :mtime
for j =1 :jstep
x =x + f(x) * deltat;
t = t + deltat;
end
tstore( m+1) = t;
xstore(:,m+1) = x';
end
end
function write_table (tstore,xstore)
%Step 4
%report X1, X2 and t
fileID = fopen ('table.txt','w');
fprintf(fileID, ' t x(1) x(2)\r\n');
fprintf(fileID, '------ -------- ---------\r\n');
for m = 1 : length (tstore)
fprintf(fileID,'%6.3f %9.6f %9.6f\r\n',...
tstore(m), xstore(1,m), xstore(2,m));
end
end
% Step 5:
function plot_graph_1(tstore,xstore)
%plot results time dependence of x(1) and x(2)
plot (tstore,xstore(1,:),'r-o',...
tstore,xstore(2,:),'b-o')
xlabel('{\it t}')
ylabel('{it\ x}_{1}, {\it x}_{2}')
title('Time dependence of {\it x}_{1} and {\it x}_{2}')
axis ([0 0.5 0 1])
end
function plot_graph_2 (xstore)
%plot results:phase portrait of x(1) and x(2)
plot(xstore(1,:), xstore(2,:),'r-o')
xlabel('{\it x}_{1}')
ylabel('{\it x}_{2}')
title('phase portrait of {\it x}_{1} and {\it x}_{2}')
axis([0 1 0 1])
end
x1=[1,0.5,0,0,0,0.5];
x2=[0,0.5,1,0.5,0,0];
for i=1:length(x1)
%now we need results for ith value of x1 and x2
[tstore, xstore] = solve_euler (@f_example, 0, [x1(i),x2(i)], 0.0005,100,15);
write_table(tstore, xstore);
figure(1)
plot_graph_1(tstore,xstore);
hold on
figure(2)
plot_graph_2(xstore);
hold on
end
end

Star Strider on 18 Sep 2019
It works when I run it, and with:
q = which('table.txt', '-all')
type(q{:})
produces:
t x(1) x(2)
------ -------- ---------
0.000 0.500000 0.000000
0.050 0.287527 0.215511
0.100 0.203881 0.291050
0.150 0.170115 0.315941
0.200 0.155981 0.323072
0.250 0.149770 0.324344
0.300 0.146874 0.323933
0.350 0.145433 0.323218
0.400 0.144670 0.322596
0.450 0.144244 0.322141
0.500 0.143997 0.321830
0.550 0.143849 0.321626
0.600 0.143759 0.321493
0.650 0.143704 0.321409
0.700 0.143669 0.321356
0.750 0.143648 0.321322
This seems to be what you want.
Note that you are writing to a file, so you need to actually print the file if you want to see the output!