How do I get two values of a function when using a loop?

조회 수: 1 (최근 30일)
Jose De La Pena
Jose De La Pena 2019년 12월 8일
편집: Stephen23 2019년 12월 8일
%Ball Trajectory Graph
%Define the for loop first
velocity= [30,40,47.16];
angle=[5,7.5,10,30,45,60];
for ii=1:length(velocity) %Does the this part of the loop 3 times
velocity_=velocity(ii); %Selects the elements of the velocity vector
for iii=1:length(angle) %Does this part of the loop 6 times
angle_=angle(iii); %Selects the elements of the angle vector
output(ii,iii) = DeLaPena_Trajectory(velocity_,angle_); %Puts the outputs in one matrix, but only the x....
end
end
So, I have this code to calculate the velocity however, the problem with it is output(ii,iii) line of code, it puts just ONE of the outputs into a matrix, I want the [x,y] not just the x. I know the output(ii,iii) is putting the outputs into a matrix, but when I use the anonymous function I always put [x,y]=...... and that gives me both values. Any hints on how I would also get the y value to be able to graph them?

채택된 답변

Stephen23
Stephen23 2019년 12월 8일
편집: Stephen23 2019년 12월 8일
You are only calling the function with one output argument. If the function returns two output arguments and you want both of those output arguments then you need to call the function with both output arguments:
[outX(ii,iii),outY(ii,iii)] = DeLaPena_Trajectory(...)
Your code would be more robust if you preallocate the outputs before the loops:
For example:
velocity = [30,40,47.16];
angle = [5,7.5,10,30,45,60];
Nv = numel(velocity);
Na = numel(angle);
outX = nan(Nv,Na);
outY = nan(Nv,Na);
for ii=1:Nv
for jj=1:Na
[outX(ii,jj),outY(ii,jj)] = DeLaPena_Trajectory(velocity(ii),angle(jj));
end
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by