How to create multiple arrays for multiple outputs of a function in a for loop
18 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I have created my own matlab function that gives 2 outpus for 4 inputs. I then created a for loop where one of the inputs changes and call the function. It works fine but I need all the values that are output for the two output values to be stored in separate arrays.
Here is my working code:
theta_launch=0;
dt=1e-6;
D_targ=100;
v_init=120;
theta_values=[]
for theta_launch=0:pi./32:pi./4
[y_impact,TOF] = myPotatof_GRT(theta_launch,dt,v_init,D_targ)
theta_values=[theta_values theta_launch]
end
I have the theta_values coming out in an 1x9 array just like I want, however when I try and do a similar thing with my y_impact and TOF values, I get error message after error message. I've tried several differnt things but nothing seems to work.
Thnak you in advance.
Yes this is for a class, however what I have compleated above I have already turned into my instructor for grading and would just like to finish it on my own because he doen's get around to grading and providing the solutions for about a week, and I would like to get this sorted before my next assignment.
0 comentarios
Respuestas (1)
Stephen23
el 18 de Nov. de 2020
Editada: Stephen23
el 18 de Nov. de 2020
In MATLAB it is generally much better to loop over indices, rather than looping over data values:
dt = 1e-6;
D_targ = 100;
v_init = 120;
T = 0:pi./32:pi./4;
N = numel(T);
Y = cell(1,N);
Z = cell(1,N);
for k = 1:N % loop over indices!
[Y{k},Z{k}] = myPotatof_GRT(T(k),dt,v_init,D_targ);
end
The two cell arrays Y and Z contain all of the function outputs:
2 comentarios
Stephen23
el 19 de Nov. de 2020
Editada: Stephen23
el 19 de Nov. de 2020
"Is there a way to avoid this being in cell arrays?"
Of course, you can use indexing to allocate data to any array type.
You need to know the sizes of the function outputs, then you can preallocate the arrays before the loop to appropriate sizes, and use indexing inside the loop to allocate the data. For example, if the function outputs are both scalar:
D_targ = 100;
v_init = 120;
T = 0:pi./32:pi./4;
N = numel(T);
Y = nan(1,N);
Z = nan(1,N);
for k = 1:N % loop over indices!
[Y(k),Z(k)] = myPotatof_GRT(T(k),dt,v_init,D_targ);
end
Ver también
Categorías
Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!