Saving data in a 3d array in for loop
14 views (last 30 days)
Show older comments
Hi! I am running a 6 equation ode solver which generates a 1001x6 matrix in a for loop. I am trying to generate a 3d matrix (1001x6xi) which stores the data after each iteration and plot the resultant values against i, but I end up getting all zeros as my values. Is there anything wrong with my code?
Here's my code:
for i=1:1:351
initial_f=[0 0 (i-51)*1e-6 0 0 0];
%ODE solver
t=(0:10:10000)*1e-15;
options=odeset('reltol',1e-15,'abstol',1e-20);
[t,f]=ode15s('lorentz_force',t,initial_f,options);
%preallocate F (3d matrix)
F=zeros(1001,6,i);
F(:,:,i)=f(i);
%extracting values
X=F(:,1,:);Y=F(:,2,:);Z=F(:,3,:);
PX=F(:,4,:);PY=F(:,5,:);PZ=F(:,6,:);
p_x=PX(1001,:);
p_y=PY(1001,:);
p_z=PZ(1001,:);
p_r= sqrt((p_x.^2)+(p_y.^2)+(p_z.^2));
Energy_total=sqrt(((p_r).^2).*(c^2)+((m^2)*(c^4)));
Energy_initial=m*c^2;
Energy_gain=Energy_total-Energy_initial;
%plotting against i
plot((i-51)*1e-6,Energy_gain./e)
xlabel ('z_0 (m)')
ylabel ('Energy Gain (eV)')
end
end
The six equations are stored in another function 'lorentz_force'. Thank you so much in advance!
0 Comments
Answers (1)
KSSV
on 29 Jun 2017
F = rand(1001,6) ;
% conver F into 3D
% using loop
F3D = zeros(1001,1,6) ;
for i = 1:6
F3D(:,:,i) = F(:,i) ;
end
% reshaping
F1 = reshape(F,1001,1,6) ;
0 Comments
See Also
Categories
Find more on Ordinary Differential Equations 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!