This question already has answers here:
Is it possible to define more than one function per file in MATLAB, and access them from outside that file?
(9 answers)
Closed 7 years ago.
How can i write code after defining a function in matlab?
I would have separated them but I have to submit my homework as whole, one .m file.
It gives the following error "This statement is not inside any function.". I tried the answers in the web but it wont work.
My .m file starts with defining the function and after the end statement, after the definition I start writing my code. And I use my function defined above in the code
Thanks very much.
You should do it the other way round.
Just wrap your 'normal' script in a function. Then, the other functions you can declare at the end of the file. E.g., if your file is called myHomework.m
function myHomework() % Should match the filename!
n=6;
if n>5
x = someFunction(n);
disp(x);
end
end % Although this 'end' can usually be omitted, not now!
function out=someFunction(in)
...
end
Related
Short version of question
In recent versions of Matlab (I have seen it in R2014b and R2015a on Windows), when you type help foo you get a brief description of the function and its signatures. For example, typing help bsxfun produces something like this (only with better format):
This MATLAB function applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled.
C = bsxfun(fun,A,B)
Reference page for bsxfun
See also arrayfun, repmat
Other uses of bsxfun
distcomp/bsxfun
This is of course only a summary of the actual documentation. To get the full documentation you need to type doc foo. This opens the HTML help browser, which takes quite some time (at least on some computers).
Is there a way to get the full help in the command window (thus avoiding the help browser), as it used to be in older Matlab versions?
Long version of question
To look into this in more detail, I'll define "old" Matlab versions as those that don't have HTML help, and "new" versions as those that do. I also need to give each type of help a name, in order to refer to them:
FP (Full, Plain): full help in the form of plain text, shown in Matlab command window (old style).
SH (Summarized, HTML): summarized help in the form of HTML, shown in Matlab command window.
FH (Full, HTML): full help in the form of HTML, shown in the help browser.
As is well known, the text for FP help is contained in the first comment lines in the file defining the function. In new Matlab versions, functions may also have an associated HTML file. This file contains SH help in an HTML tag, and FH help in HTML code.
Possible behaviour is:
In old Matlab versions, help foo produced FP help.
In new Matlab versions, help foo produces SH help if foo has an associated HTML help file, and FP help if it doesn't.
In new Matlab versions, doc foo produces FH help if foo has an associated HTML help file. If it doesn't, FP help is shown in the help browser (without format).
So the problem is more properly phrased as: how to show FP help in new Matlab versions when foo has an associated HTML help file. The question is meaningful because
Most Matlab functions do have an associated HTML help file.
Most Matlab functions, even built-in functions (that have no m-code), have and m-file containing FP help.
An additional motivation is that in some cases the FP documentation contains features that don't appear in the FH documentation (see for example here).
Original answer (Matlab versions R2014b, R2015a)
Although the documentation doesn't tell, the help function in these Matlab versions supports zero, one or two output arguments. You can check this typing open help and looking at the function signature:
function [out, docTopic] = help(varargin)
In essence, help works internally as follows:
It creates an object called process, of class helpUtils.helpProcess, by calling the class constructor as:
process = helpUtils.helpProcess(nargout, nargin, varargin);
where nargout, argin and varargin are those with which help was called.
It runs the method process.getHelpText, which calls the undocumented, built-in function helpfunc, and as a result sets the property process.helpStr. This property contains the help string which is shown in the command window.
As it turns out, at least on Windows, depending on the value of nargout (which gets passed to the constructor helpUtils.helpProcess) the resulting help string will be FP or SH. Namely, it will be FP if nargout>0, and SH if nargout==0. You can check this by typing the following code (adapted from help.m) directly in the command window:
process = helpUtils.helpProcess(1, 1, {'bsxfun'});
process.getHelpText
process.helpStr
This will produce FP help. On the other hand, changing the first 1 (which corresponds to nargout in the actual call) into a 0,
process = helpUtils.helpProcess(0, 1, {'bsxfun'});
process.getHelpText
process.helpStr
will produce SH help.
I don't know why this is so, that is, how it works on a deeper level than this. All I know is that the getHelp method calls the undocumented helpfunc, which is at least involved in producing FP help.
So, to get FP help you need to call help with one or two output arguments. For example,
str = help('foo')
assigns the FP help text to variable str and displays it. Or you can use
disp(help('foo'))
which also has the effect of calling help with an (implicit) output argument.
To have this behaviour from the standard command help foo, you could define a help function to override Matlab's help, and place it in your Matlab document folder. This folder normally appears first in the path (or you can make sure it does by editing startup.m), and thus has precedence. The new function will essentially call Matlab's help with one output argument, and then display the resulting (FP) help text. In order to call the overriden function it is necessary to temporarily change to its folder:
function help(varargin)
if isempty(varargin)
varargin = {'help'}; %// `help` should be equivalent to `help help`
end
d = pwd; %// take note of current folder
cd(fullfile(matlabroot, 'toolbox', 'matlab', 'helptools')) %// folder where the
%// standard `help` function is
disp(help(varargin{1}));
cd(d) %// restore folder
So now, finally, help foo produces the old-style (FP) help.
Edit for Matlab version R2015b
In Matlab R2015b the behaviour seems to have changed for the better. Typing help foo no longer produces SH help. It's not exactly FP either. In fact it's better than that: it produces FH help but in the command Window, not in the browser. Or, equivalently, it produces FP help but with links and better formattting.
So no need to tweak anymore!
Edit for Matlab version R2018a
Matlab R2018a again gives SH help. The solution provided in this answer works (that is, produces FP help).
So back to tweaking!
A better way is to include the full path to the function when using the help command, then old style full help is displayed and the links also work, e.g. try:
help surf
help(fullfile(matlabroot, 'toolbox', 'matlab', 'graph3d', 'surf.m'))
I’ve just submitted an override help function based on this to MATLAB FEX:Full Command Line Help
This question already has answers here:
Create variables with names from strings
(6 answers)
Closed 7 years ago.
Assume the variable FileName contains a string such as Name1. How do I make a variable with the name Name1?
The example 4 at this page seems to be similar, but I cant get it to work. Is it the right way to do it?
http://se.mathworks.com/help/matlab/ref/genvarname.html
What you see in "Example 4" is accused as bad programming style. The documentation also contains a section why to avoid eval.
I would recommend a struct with dynamic field names to achieve similar.
filename='name1';
mydata=struct();
mydata.(genvarname(filename))=load(filename);
Besides better performance, you also get additional functionality when handling multiple files. For example structfun to apply a function to all your data or fieldnames to get all filenames.
For what you want to do, the eval function is there for you:
FileName = 'Name1';
eval([FileName ' = 18;']); % Executes "Name1 = 18;"
and now the variable Name1 is created and has a value of 18.
The function genvarname has a different purpose, which is to generate acceptable and non-conflicting variable names, and not the variables themselves.
This question already has answers here:
Are forward declarations supported in MATLAB?
(2 answers)
Closed 8 years ago.
I would like to have a file with function AND with little code that calls that function, for example:
function foo()
...
end
foo()
I would like to save such code to file (one file) named "everything.m", and then type in "everything" in Matlab/Octave console my function foo would be defined AND called.
The common way to do this sort of thing is to have a script called everything.m
% everything.m
foo();
and one file for each function you want to be able to use:
% foo.m
function foo()
...
end
Executing everything.m then calls all the functions you want to call (plus any additional tasks you might want to do at that stage).
Having all your functions on the Matlab path, means they are "defined" (accessible from the Matlab command prompt or inside other functions). This is "the Matlab way" :)
Note that it is possible to have more than one function per file,
% bar.m
function bar()
otherFunction(); % WORKS OK
end
function otherFunction()
...
end
only the topmost function will be visible in the Matlab command prompt:
>> bar
>> % no error
>>
>> otherFunction
??? Undefined function or variable 'otherFunction'.
In Matlab you cannot mix scripts and functions. So in your case, in order to call foo() you need to write another function otherwise the matlab compiler will complain.
So everything.m should have a function called everything, where you can call foo() from
There is a similar question here
MATLAB script code and function code in the same file?
I think you can write the code in a script and then save it with the same name of the function. For example if your function is foo, than when you save the file, its name has to be : foo.m . Calling foo from your command line executes the function. If you want to call the function only without input arguments, you have to define all the variables you need between the keywords "function" and "end". Also you can call the function successfully only if your current folder is the one where you saved the function. If you would call that function from another directory, you'll get an error. To make the function work "globally" you should add it to the "matlab path". Hope this helps you a bit.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Suppressing a function’s command window output
Suppress Output
Is there a way to "silence" the output of a Matlab function? In other words, if a function generates some displayed text in the command window, is there a way to run it in a quiet mode, where the output is suppressed?
In my case, I am using a third-party function iteratively that displays a lot of text, and I want to find a way to suppress that text without modifying the function itself. I'm thinking there must be some kind of wrapper function like quiet(thirdpartyFunction) that gives this kind of behavior. Or is this wishful thinking?
You can probably use evalc and discard the return value.
I just discovered (to my surprise) that calling the following function
function foo()
if false
fprintf = 1;
else
% do nothing
end
fprintf('test')
gives and error Undefined function or variable "fprintf". My conclusion is that the scope of variables is determined before runtime (in my limited understanding how interpretation of computer languages and specifically Matlab works). Can anyone give me some background information on this?
Edit
Another interesting thing I forgot to mention above is that
function foo()
if false
fprintf = 1;
else
% do nothing
end
clear('fprintf')
fprintf('test')
produces Reference to a cleared variable fprintf.
MATLAB parses the function before it's ever run. It looks for variable names, for instance, regardless of the branching that activates (or doesn't activate) those variables. That is, scope is not determined at runtime.
ADDENDUM: I wouldn't recommend doing this, but I've seen a lot of people doing things with MATLAB that I wouldn't recommend. But... consider what would happen if someone were to define their own function called "false". The pre-runtime parser couldn't know what would happen if that function were called.
It seems that the first time the MATLAB JIT compiler parses the m-file, it identifies all variables declared in the function. It doesn't seem to care whether said variable is being declared in unreachable code. So your local fprintf variable immediately hides the builtin function fprintf. This means that, as far as this function is concerned, there is no builtin function named fprintf.
Of course, once that happens, every reference within the function to fprintf refers to the local variable, and since the variable never actually gets created, attempting to access it results in errors.
Clearing the variable simply clears the local variable, if it exists, it does not bring the builtin function back into scope.
To call a builtin function explicitly, you can use the builtin function.
builtin( 'fprintf', 'test' );
The line above will always print the text at the MATLAB command line, irrespective of local variables that may shadow the fprintf function.
Interesting situation. I doubt if there is detailed information available about how the MATLAB interpreter works in regard to this strange case, but there are a couple of things to note in the documentation...
The function precedence order used by MATLAB places variables first:
Before assuming that a name matches a function, MATLAB checks for a variable with that name in the current workspace.
Of course, in your example the variable fprintf doesn't actually exist in the workspace, since that branch of the conditional statement is never entered. However, the documentation on variable naming says this:
Avoid creating variables with the same name as a function (such as i, j, mode, char, size, and path). In general, variable names take precedence over function names. If you create a variable that uses the name of a function, you sometimes get unexpected results.
This must be one of those "unexpected results", especially when the variable isn't actually created. The conclusion is that there must be some mechanism in MATLAB that parses a file at runtime to determine what possible variables could exist within a given scope, the net result of which is functions can still get shadowed by variables that appear in the m-file even if they don't ultimately appear in the workspace.
EDIT: Even more baffling is that functions like exist and which aren't even aware of the fact that the function appears to be shadowed. Adding these lines before the call to fprintf:
exist('fprintf')
which('fprintf')
Gives this output before the error occurs:
ans =
5
built-in (C:\Program Files\MATLAB\R2012a\toolbox\matlab\iofun\fprintf)
Indicating that they still see the built-in fprintf.
These may provide insight:
https://www.mathworks.com/help/matlab/matlab_prog/base-and-function-workspaces.html
https://www.mathworks.com/help/matlab/matlab_prog/share-data-between-workspaces.html
This can give you some info about what is shadowed:
which -all
(Below was confirmed as a bug)
One gotcha is that Workspace structs, and classes on the path, have particular scoping and type precedence that (if you are me) may catch you out.
E.g. in 2017b:
% In C.m, saved in the current directory
classdef C
properties (Constant)
x = 100;
end
end
% In Command window
C.x = 1;
C.x % 100
C.x % 1 (Note the space)
C.x*C.x % 1
disp(C.x) % 1