I am trying to convert the attached script into a function to produce the same figure and results for a plot of the (for argument's sake) Earth orbiting the Sun. I have attached what I have of the function so far, but I am struggling to understand what I have done wrong and how to proceed. The function has pseudocode explanations of variables etc. Any help would be much appreciated. Regards, AR

댓글 수: 4

Rik
Rik 2017년 5월 3일
There isn't really that much of a difference in this case between a function and a script. The main differences are execution speed optimization and workspace management. So once you have a working script, just add the function line at the top, an end at the bottom, and move some definitions from code to input.
It looks like you are already there. What is your problem exactly?
Jan
Jan 2017년 5월 3일
Whenever you mention in the forum, that you assume something is going wrong, explain the details. Why do you think, that you have done something wrong? It is much easier to solve a problem than to guessm what the problem is.
Ashley Rains
Ashley Rains 2017년 5월 3일
Thank you for your quick replies. I think I am not understanding the ways to reference into the matrices, and then pack them back into return values. The errors that return when attempting to execute that function are to do with the matrix dimensions and certain variables being undefined/not existing. Apologies, but I do not have access to Matlab until tomorrow, so please bear with me until I can try to solve the problem, I will reply again soon. Regards, AR
Ashley Rains
Ashley Rains 2017년 5월 4일
Finally got it sorted! Found some absolutely stupid re-used variables that were throwing everything out. Many thanks for the answers.

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

 채택된 답변

Adam
Adam 2017년 5월 3일

0 개 추천

There may be other things wrong, but these 2 lines are surely not what you want. You pass in p and v as input arguments, then you just set them to empty here:
p = []; % Celestial body initial positions vector
% Will be N by 2 e.g. p1 = [px,py]
v = []; % Celestial body initial velocities vector
% Also N by 2 e.g. v1 = [vx,vy]
It's not obvious what all the lines of code above this are all about either - they seem somewhat pointless.
You need to use the input arguments that you pass in - e.g. mass, not m as you do further down the code (or you could change your input argument name to 'm', but I much prefer 'mass' as it says what it is, 'm' is meaningless).
The biggest difference between a function and script is the arguments that you pass into it instead of creating within the function. Never over-write the input arguments!

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Data Type Identification에 대해 자세히 알아보기

질문:

2017년 5월 3일

댓글:

2017년 5월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by