I have just made a script randArrGen.m that generates an array of n floating point numbers, which needs to be used as a function within another scipt, but I'm struggling to understand how to turn it into a function. In my head it seems easier just to run this script within the other script when required. The a and b values aren't massively important and are just to give a range for the floating point numbers to be within (I though -1000 and 1000 were good boundaries).
% randArrGen generates an array of n floating point numbers, where n is a
% value inputted by the user.
n = input("How many values do you wish to have in the array?");
Thanks. I didn't realise it would be that simple. I'm super new to coding stuff, so I'm wrapping my head around the basics currently. Would this then just be saved as the randArrGen.m file I already have?
You could also put it into a script, down at the bottom of the script after all the script commands, but you'd need to finish off randArrGen() with an "end" statement. If it's in its own m-file, an end statement is not required - it's optional. But if it's in a script, only that script can see it and run it - no other functions or scripts can see it or run it.
If I had the file randArrGen.m in the same folder as my script I wish to call it in, what would be the best way to run it, and would it be better to ask for the value n in the main script, rather than as part of the function? Sorry if these are really stupid questions.
I'm trying to do something like randArrGen(5) to get it with the n value being 5, or whatever else I put in there.
EDIT: I just figured it out. If I have n in the bracket in the function line and do the following, it works.
function array = randArrGen(n)
% randArrGen generates an column vector of n floating point numbers,
Most people would probably ask the user for parameters before calling the function. You could use inputdlg() to ask for n, a, and b with defaults. Then to call it:
Main script:
array = randArrGen(n, a, b);
File : randArrGen.m
function array = randArrGen()
% randArrGen generates an column vector of n floating point numbers, in the range [a, b],
% where n, a, and b are values passed in through the input argument list.
The main script where I have to use the function has a line to ask for the parameter for n, and I'm keeping a and b set at specific values just to give a nice range that isn't too massive. Thank you for the help with this. It's starting to make a lot more sense to me.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
0 Comments
Sign in to comment.