Hello! I'm extremely new to Matlab, and I'm working on a homework problem, and I keep coming up with an error... I've written my functions, and defined some variables to be plugged into them. I can't even call my functions, because I get the error for writing them.
This all has to be in one m-file so I cannot save the functions in different ones... I'm not sure what to do :(
function [x,y,vx,vy] = trajectory(t,v0,th0,h0,g)
x = v0 .* cos(th0) .* t; y = h0 + (v0 .* sin(th0) .* t) - ((1./2) .* g .* (t.^2)); vx = v0 .* cos(th0); vy = (v0 .* sin(th0)) - (g .* t);
function y = height(t,v0,th0,h0,g)
[x,y,vx,vy] = trajectory(t,v0,th0,h0,g);
%(b) v0 = 20; th0 = 45; h0 = 5; g = 9.81; t = linspace(1,4,400);
y = height(t,v0,th0,h0,g)
No products are associated with this question.
You need to understand the difference between M-script and M-function.
If the first line of your .m file is a function definition like you have in the code. This .m file is a M-function.
If the first line of your .m file is not a function definition, but other M command or M code, the .m file is called M-script.
You can not have M-function definition in M-script. That is the error message tries to tell you.
You can save the two functions you have in two .m file and then write a script to call the function.
Please vote here to voice your request. http://www.mathworks.com/matlabcentral/answers/7690-please-vote-if-you-want-to-have-m-function-in-m-script
In addition to what Fangjun wrote:
When you are not already executing within a given file, MATLAB can only find the very first function in that file, and that first function name must be the same name as the file.
Therefore, the order of functions in the file should be that the very first one is the "driver" function (the one that sets up everything and calls the other functions to do the work), and the functions that do the internal work should be after that in the file.
If you look at the function order you have coded above, you have coded the internal routine first, and then coded a routine that calls that internal routine. You would, however, not be able to activate that second routine from the MATLAB command line.
So... what you need to do is take the line that start at %(b) through to the end of the file, and move those lines to the beginning of the file, and then you have to insert a "function" line at the very top, naming it appropriately for your assignment conditions. I can see from the code that those lines set things up and then call the internal routines, so those lines should be in the first function.