필터 지우기
필터 지우기

How to create multiple arrays for multiple outputs of a function in a for loop

조회 수: 18 (최근 30일)
Gen
Gen 2020년 11월 18일
편집: Stephen23 2020년 11월 19일
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.

답변 (1개)

Stephen23
Stephen23 2020년 11월 18일
편집: Stephen23 2020년 11월 18일
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
Gen
Gen 2020년 11월 18일
Is there a way to avoid this being in cell arrays? He doens't have us using cell arrays in this, the provided answers are not in cell arrays just regualr arrays. This also only outputs the two y_impact and TOF where as it still needs to output theta_vals.
Stephen23
Stephen23 2020년 11월 19일
편집: Stephen23 2020년 11월 19일
"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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by