How to store an array coming from a for loop within a function?
Mostra commenti meno recenti
Hello, I'm trying to store a vector (num_fval) and a cell array (u) coming from a for loop performed inside a function. Here it is the code:
%Numerical solutions
f=@(t,Y)eq3(t, Y); % We need to define the equation in a matlab function, because we need to calculate also the Jacobian
for i = 1:50
N(:,i) = 1+11*i-i; % number of points
t0 = 0; T = 3; % initial and final time
y0 = 0; % initial point
h(:,i) = (T-t0)/(N(:,i)-1); % step size
Tu{:,i} = t0:h(:,i):T;
Ti = Tu{i}; % time mesh
[t, u, num_fval] = Euler1(f, [t0 T], y0, Ti, i);
%Analitical solution
init_val = ['y(0)=' num2str(y0)];
sol=dsolve('Dy=-y+t',init_val);
fsol= inline(vectorize(sol));
figure;
plot(t,u{i});
xlabel('t');grid;
hold on
plot(t,fsol(t));
leg=legend('u_E','y');set(leg,'location','best');
title('y''=-y+t, y(0)=0 t\epsilon[0,3]');
% Computational cost and accuracy
u_true=fsol(t);
Errl = abs(u_true-u{i});
AbsErr=norm(Errl);
RelErr=AbsErr/norm(u_true);
num_fval(:,i); % number of evaluations of the function f for the explicit Euler solver
format long
disp(strcat("Table 1 Computational cost and accuracy of each method"));
columnNames = {'num_fval','h','RelErr'};
a = {num_fval(1,i),h(1,i),RelErr};
Results = cell2table(a,'RowNames',{'Euler'});
Results.Properties.VariableNames = columnNames;
disp(Results);
end
This is the function:
%Euler1
function [t, u, num_fval] = Euler1(f,tspan,u0,Ti,i)
% u0 column vector
% Ti is the vector of the discrete time steps: Ti(n)=t0+(n-1)h, n=1,...,N
N=length(Ti);
u=cell(1,N);
u{i}(:,1)=u0;
for k=2:N
u{i}(:,k)=u{i}(:,k-1)+(Ti(k)-Ti(k-1))*f(Ti(k-1),u{i}(:,k-1));
num_fval(:,i)=N-1;
t=Ti;
end
Despite the fact that u results to be an empty cell array and num_fval a vector with only the last element different from zero, I'm still able to plot u and show num_fval in Table 1 for each cycle. Why? And how can I store succesfully both u and num_fval? I need them to plot num_fval vs h and RelErr vs h.
Thanks in advance to everyone.
Risposte (0)
Categorie
Scopri di più su Programming in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!