Converting 2D matrix to 3D

for alpha = 1:90
v0 = 200;
g=9.81;
y0(1) = 0;
y0(2) = v0*sind(alpha);
y0(3) = 0;
y0(4) = v0*cosd(alpha);
tspan = 1:0.5:700;
options = odeset('Events','event_proj');
[t,y] = ode45(@proj, tspan, y0,options);
a_m(:,:,alpha) = y;
end
(Basic projectile motion equation.) I'm trying to save y-state matrix to a_m 3D-matrix. When program calculates the y values for different alphas, It will store the y matrix into 3D matris whose third dimension is same as alpha. When I try to run the code above, I get
Subscripted assignment dimension mismatch.
Error in deneme1 (line 16)
a_m(:,:,alpha) = y;
I try to assign y to another variable(say, y_d), but it gave the same error. Any thoughts? It is supposed to be very easy but I can't figure it out.
Thank you.

 Accepted Answer

You have specified tspan. In the case where your event_proj does not terminate the calculation, y will end up with the same number of rows as length(tspan) and with 4 columns. If you did not initialize a_m to a different size, then that would be fine, the output size would be consistent and you would store the 2D array without difficulty.
But... if event_proj ever terminates the calculation, then the number of rows returned in y would tend to be the number of tspan entries before the terminal time, plus one (the time of termination); in some circumstances you could end up with slightly different number of rows, I think, especially if the termination time was just a little more than one of the entries in tspan.
And in that case, y is not the right shape to store against the existing array, since it has the wrong number of rows. Also in that case, the final t entry returned is not going to be any of the entries in tspan so you cannot store positionally and expect the final used to always refer to the same tspan entry.
You can use techniques such as
a_m(1:size(y,1), :, alpha) = y;
a_m(size(y,1)+1:end, :, alpha) = nan;
this would nan-pad any short rows. But you will need to decide how you want to handle the terminal time in such cases.

More Answers (0)

Categories

Find more on Mathematics 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!