Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a massive script consisting of many code sections that I run independently of each other. For some of these code sections, there is a lot of repeating code, and so I wanted to define a function that I can call multiple times from a given code section. However, I am either getting the error "Function definitions are not permitted in this context.", or, once the code execution reaches the function call, it says the function is not defined.
So it seems that Matlab (2016b) does not accept functions to be defined within code sections, or I am doing something else that's wrong.
What I tried:
define the entire script as a function, named exactly as the name of the containing .m file, and with a corresponding 'end' on the very last line
define the function containing my repeating code either at the end of the code section for which it is relevant
.. or at the end of the file (before the top-most function's own 'end')
.. or at the end of the file (after the top-most function's own 'end')
My code organisation might be criticised, e.g. I might instead use multiple functions in my file, rather than script-style code sections. However, I would like to know whether there is a way to be able to call functions from inside code sections.
You need to read the following documentation:
Scripts and functions
Create functions in files
Notably, the second contains the relevant information:
Starting in R2016b, another option for storing functions is to include them at the end of a script file.
You say you're using R2016b, so you can define functions within scripts, but they must be at the end of the file. The documentation contains the following example of a valid script containing functions:
x = 3;
y = 2;
z = perm(x,y)
function p = perm(n,r)
p = fact(n)*fact(n-r);
end
function f = fact(n)
f = prod(1:n);
end
Related
Background
I'm planning to create a large number of Matlab table objects once, so that I can quickly refer to their contents repeatedly. My understanding is that each table variable/column is treated in copy-on-write manner. That is, if a table column is not modified by a function, then a new copy is not created.
From what I recall of C++ as of 1.5 decades ago, I could ensure that the code for a function does not modify its argument's data by using constant-correctness formalism.
The specific question
I am not using C++ in these days, but I would like to achieve a similar effect of ensuring that the code for my Matlab function doesn't change the data for selected arguments, either inadvertently or otherwise. Does anyone know of a nonburensome way to do this, or just as importantly, whether this is an unrealistic expectation?
I am using R2015b.
P.S. I've web searched and came across various relevant articles, e.g.:
http://www.mathworks.com/matlabcentral/answers/359410-is-it-possible-to-avoid-copy-on-write-behavior-in-functions-yet
http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data
(which I need clarification on to fully understand, but it isn't my priority just now)
However, I don't believe that I am prematurely optimizing. I know that I don't want to modify the tables. I just need a way to enforce that without having to go through contortions like creating a wrapper class.
I've posted this at:
* Stack Overflow
* Google groups
There is no way of making variables constants in MATLAB, except by creating a class with a constant (and static?) member variable. But even then you can do:
t = const_table_class.table;
t(1,1) = 0; % Created and modified a copy!
The reason that a function does not need to mark its inputs as const is because arguments are always passed by value. So a local modification does not modify data in the caller’s workspace. const is something that just doesn’t exist in the MATLAB language.
On the other hand, you can be certain that your data will not be modified by any of the functions you call. Thus, as long as the function that owns the tables does not modify them, they will remain constant. Any function you pass these tables to, if they attempt to modify them, they will create a local copy to be modified. This is only locally a problem. The memory used up by this copy will be freed upon function exit. It will be a bug in the function, but not affect code outside this function.
You can define a handle class that contains a table as it's preperty. Define a property set listener that triggers and generates error/warning when the value of the property changes.
classdef WarningTable < handle
properties (SetObservable)
t
end
methods
function obj = WarningTable(varargin)
obj.t = table(varargin);
addlistener(obj,'t','PreSet',...
#(a,b)warning('table changed!'));
end
end
end
This should generate warning:
mytable = WarningTable;
mytable.t(1,1) = 0;
Is there a way to access data generated in one .m file from another. What I am trying to do is I have one .m call it A.m where I have loaded a large amount of data from a .txt file and broken it up into a structure with various fields. Since this takes up a large amount of space in the script I would like to create another .m file call it B.m, in which I can access the structure created in A.m and plot and perform calculations in B.m. So, basically I want to access a structure created in A.m from B.m. Is this possible?
-Thanks
There are some things to think of here. First, to limit scope, do not use scripts: use functions instead. Calling a script from another script mainly add code to the first script and have nothing to do with scope. However, by using this method, your code becomes hard to read and understand. If you want that all code to be in the same scope I would recommend you keep all the code in the same m-file.
A function however have a function scope and unless a variable is declared global it can only be passed into this scope by using function input arguments. Also, the only way to return values is to use function output arguments.
function [out1, out2,...] = myFun(in1,in2,...)
out1 = in1*in2;
out2 = in2.^2;
...
Now to the tricky part. The variable passed into the function is passed as "copy on write", meaning that the variables are always passed as a reference unless they are modified inside the script. When using structs, only the field that is modified is copied. This can have consequences for your program as well. Since you say your data is large, changing too many fields in the struct in the same function may cause memory overflow.
Anyway, if you only uses script you do not need to pass any data, since the scope is not affected. However, I recommend you to use functions and pass the struct as an input argument. If this was not what you asked for, please comment on this answer.
I have a large project going with 40+ functions and it's just increasing every day. Often times I reference a function multiple times from different scripts. Every once in a while, I'll find that I need to edit a function for one script, and then I realize that it's possible that I want that function to stay the same for another script. Obviously this in itself is no problem; I can just write a new function. But sometimes I don't remember if I've referenced that function anywhere else in my larger folder containing all my scripts!
Is there a way in MATLAB to somehow find a count of how many times a function is used within a folder? If so, is there a way to track where it's being referenced from? Thanks in advance =).
For this I typically use the find files funcionality (found in the menu on top of your screen) with the 'contains' option. Especially if your function name does not match common variable names this works very well.
Just search in the entire matlab path, or in the specific directory for something like myFun( and you will see all the places where it is called. In the worst case you will also find some places where it is not called.
MATLAB provides support for dependency tracking using the depfun function. depfun tells you which other functions are required to run a given function.
What you're asking is the opposite problem: Which functions require a given function?
Using depfun, you can do a reverse lookup. Here's a quick example:
function result = invdepfun(allFunctions, lookFor)
% Return all functions that depend on a given function
%
% Example: invdepfun({'myfun1', 'myfun2', 'myfun3'}, 'myfun4') returns all of
% 'myfun1', 'myfun2', 'myfun3' that use 'myfun4'.
filename = which(lookFor);
result = {};
for i = 1 : numel(allFunctions)
deps = depfun(allFunctions{i}, '-quiet');
if any(strcmpi(deps, filename))
result{end + 1} = allFunctions{i};
end
end
end
You can use various other MATLAB functions (which, dir, etc.) to autmatically compile a list of all your functions to pass to invdepfun as the first argument.
See also this post on File Exchange.
I don't know of any builtin Matlab functionality that does this, so you probably have to write some function to do this for you.
You could use the DIRWALK function from Matlab FileExchange to crawl your project folder and look into all Matlab files (use the what command) searching for your function name.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm writing a sizable application using object-oriented MATLAB, and this has gotten me thinking about how to document the code. If this was C, I would use Doxygen. For Java, I'd use JavaDoc. Both have mostly agreed-upon standards for how class and method documentation should look and what it should contain.
But what about MATLAB code? The most I've seen in TMW's own classes is a short sentence or two at the top of the class, and I can't find any topics devoted to documenting sizable MATLAB applications.
So how do you document your MATLAB classes? Any particular style issues or additional tools?
I realize the question is stale, but for the benefit of Google: Matlab has a built-in feature for that. You write your comments in a certain style (a la JavaDoc) and they get picked up by the help and doc functions. It can be used to document classes, properties, and methods. It is surprisingly complete, yet a little finicky. The doc is here:
http://www.mathworks.com/help/matlab/creating-help.html
I document my oo code the following way:
At the beginning of the file that contains 'classdef', I write a summary of what the class does, and typical usage. I also explain properties in detail and I add a 1-sentence description of each method.
After each property definition, I add one explanatory sentence about it (on the same line)
Each method is documented like a function, i.e. it has a H1-line, a synopsis, and an explanation of the input and output parameters.
When you call 'doc myClass', you will see (1) at the beginning, followed by the list of properties explained by the sentences you added in (2) and the list of methods that show the H1-line and the rest of the help (3) if you click on the link.
In addition, all my classes subclass a general superclass which implements (among others) the method 'help' that calls doc(class(obj)), which allows me to bring up the help from every instance of the class.
Example
%# MYCLASS is a sample class
%# All this text will show up at the top of the help if you call 'doc myClassName'
%#
%# myClass is an example for documentation. It implements the following properties and methods:
%# PROPERTIES
%# myProp - empty sample property (some more explanation could follow here)
%#
%# METHODS
%# myMethod - sample method that calls doc
%#
classdef myClass
properties
myProp = []; %# empty sample property
end %# properties
methods
%%# MYMETHOD -- use %% so that you can easily navigate your class file
function myMethod(obj)
%#MYMETHOD calls up the help for the object
%#
%# SYNOPSIS myMethod(obj)
%# INPUT obj: the object
%# OUTPUT none
%#
try
doc(class(obj))
catch
help(class(obj))
end
end %#myMethod
end %#methods
end %#myClass
Edit 1 If you want a nice html documentation, you can, in addition, use m2html to generate it for you. M2html will collect the help texts and it can even do dependency graphs.
Edit 2 While m2html documents standard Matlab code nicely, it has no specific support for classes. This means that you get the methods as 'subfunctions' linked in the class, but you do not get as nice a summary as you'd get with Doxygen, or which you get with the built-in documentation browser.
Try Sphinx with the matlabdomain extension. Sphinx is a Python package that auto-documents code using ReStructuredText (rst) markup. The extension sphinxcontrib-matlabdomain allows auto-documentation of MATLAB code that uses rst markup recognized by Sphinx in its docstrings. Send bugs and suggestions to the issue tracker on BitBucket.
For example, the following code in my_project/my_fun.m:
function [outputs] = my_fun(args)
% MY_FUN does really cool stuff
% [OUTPUTS] = MY_FUN(ARGS)
%
% :param args: Input arguments
% :type args: cell array
% :returns: outputs
% :raises: :exc:`my_project.InvalidInput`
code ...
end
would be documented in an rst file like this:
.. _my-project
My Project
==========
.. automodule:: my_project
This folder contains all the functions and classes for my project.
My Function
-----------
.. autofunction:: my_fun
and would produce html (or pdf, latex, and many others) like what is shown on this blog post.
There exists a Doxygen-Adapter for M-Files on FileExchange, see http://www.mathworks.com/matlabcentral/fileexchange/25925-using-doxygen-with-matlab.
Say I had the following code:
% Cellmode_subfunction_test.m
%% Cell 1
foo(1);
%% Cell 2
foo(2);
%% Definition of the foo subfunction
function foo(num)
disp(['num=' num2str(num)]);
How can test cell 1 and cell 2 with the subfunction defined at the end?
Edit: Basically each of the cells in this example perform some lengthy calculations so I'd like to test and debug them separately. I'm using subfunctions to abstract out and reuse common functionality and since so far this functionality is only used in this particular application I don't really want to place foo in a separate m-file.
Edit(2): I just remembered that I vaguely recall cell mode only working in matlab scripts and not in function m-files and that subfunctions and nested functions are not allowed in such scripts. Thus what I'm asking for is probably not possible.
Although the anonymous function solution given below is perhaps somewhat restrictive as it only allows single expression functions, it did in fact suffice for what I wished to do and hence I've accepted it as a solution to my problem.
CORRECTION:
I misunderstood your use of the word CELL. My apologies. It appears you simply want to define a function at the command line without saving it to a .m file. For this, you can use anonymous functions:
foo = #(num) disp(['num=' num2str(num)]);
Then you can use "foo" as you would any other function.
The way that I normally handle that is by using dbstop somewhere inside of the main function. Then you have access into all of the functions which the main function would normally have access to. If you're working with the ML editor, just use a breakpoint at the first call to foo.
Hope it helps.
Dan