How can I get a persistent counter in a Matlab function without an `isempty` hack? - matlab

I would like to add a counter to a function so it knows how many times it has been called.
Here is what I am currently using.
function Foo ()
persistent counter;
if (isempty(counter))
counter = 0
end
counter = counter + 1
end
Line 3-5 looks like a hack.
How can I directly initialize counter to 0 without having it reset or using isempty?

Merlin, isempty(marker) should be isempty(counter) but I'm sure that's what you meant. The code you have is what the matlab documentation recommends if you look here and here. Additionally, this is also what Loren uses as well. So what you have is correct (sorry if this answer is not satisfying).

Related

Counter doesn't count up

while True:
def update():
global counter
global points
counter = points
counter = 0
points = counter + 1
print(points)
First off I am very new to this I am wonder my simple counter only print 1 instead of counting up.
Your indentation is off. Also some of your code seems to not be of use for what you're outputting.
Try this:
counter = 0
while True:
counter = counter + 1
print(counter)
I'm not sure why you are using two variables. The points variable isn't doing anything. Also you never call the update() function if you were trying to do that.
Maybe go read the Python Tutorial? Because you seem a little lost.
Happy Coding!
When posting Python please take care to maintain the indents (the spaces before each line of your code), because they are critical to how Python programs work.
You have placed the definition of the update() function inside the while loop. Defining a function is not the same as running it, so the update would not actually be carried out as part of the loop. There is pretty much no reason to put a function definition inside a while loop.
It would also be better for update() not to be a function, since it depends on both variables being global and does not really have any useful function once parameterized.
The reset of counter to 0 is also inside the loop. This means that the counter resets every time around the loop, which is why it keeps printing 1.
This will work, although unless you have a reason for using the variable points it would be better not to since you only actually need counter:
counter = 0
while True:
points = counter + 1
counter = points
print(points)
A python program,print a number starting from 0.
def update():
counter = 0
while(True):
print(counter)
counter = counter + 1
update()

clearer explanation of function level scope for recursion

This is an example from the book 'Matlab for Neuroscientists'. I don't understand the order in which, or why, g gets assigned a new value after each recursion. Nor do I understand why "factorial2" is included in the final line of code.
here is a link to the text
Basically, I am asking for someone to re-word the authors explanation (circled in red) of how the function works, as if they were explaining the concept and processes to a 5-year old. I'm brand new to programming. I thought I understood how this worked from reading another book, but now this authors explanation is causing nothing but confusion. Many thanks to anyone who can help!!
A recursive method works by breaking a larger problem into smaller problems each time the method is called. This allows you to break what would be a difficult problem; a factorial summation, into a series of smaller problems.
Each recursive function has 2 parts:
1) The base case: The lowest value that we care about evaluating. Usually this goes to zero or one.
if (num == 1)
out = 1;
end
2) The general case: The general case is what we are going to call until we reach the base case. We call the function again, but this time with 1 less than the previous function started with. This allows us to work our way towards the base case.
out = num + factorial(num-1);
This statement means that we are going to firstly call the function with 1 less than what this function with; we started with three, the next call starts with two, the call after that starts with 1 (Which triggers our base case!)
Once our base case is reached, the methods "recurse-out". This means they bounce backwards, back into the function that called it, bringing all the data from the functions below it!It is at this point that our summation actually occurs.
Once the original function is reached, we have our final summation.
For example, let's say you want the summation of the first 3 integers.
The first recursive call is passed the number 3.
function [out] = factorial(num)
%//Base case
if (num == 1)
out = 1;
end
%//General case
out = num + factorial(num-1);
Walking through the function calls:
factorial(3); //Initial function call
//Becomes..
factorial(1) + factorial(2) + factorial(3) = returned value
This gives us a result of 6!

Matlab: recursive algorithm to return the run count easily without profiler?

I would like to get the number of iterations that the recursive mlfnonneg requires. Currently, I use profiler for this but it would be more useful to get the number as a return value from the function. Is there any easy way to get it?
I measure the running time of a function like this
h=#() mlfnonneg(lb,ub,mlfBinCor,method);
tElapsed=timeit(h);
and now the function mlfnonneg should return the number of iterations. I have considered adding a ticker that the function always returns but I don't know how to get the return value after using timeit. How to get the running time and the running count of the recursive algorithm elegantly?
You can always add an optional return value to a function which you can use as a counter. Something like this:
[... count] = f(...)
% Do stuff here
if <some condition>
% Recurse
[... count] = f(...);
count = count + 1;
else
% Terminal condition
count = 1;
end
You should just call your function one more time to get the count. This should not be a significant problem, since timeit actually performs multiple calls to your function to get an average metric.
I don't know if this is an option for you - but you could create a global variable IT_COUNT that you declare both at the top level, and inside your function.
Before calling timeit() you set the variable to zero; inside the routine you increment it for every loop. When the function returns you print out the result - and there is your answer.
It does depend on you being able to modify the code to mlfnonneg to include the counter. I don't see an easy way around that, but maybe others have a better idea.
update inspired by Luis Mendo's (now deleted) answer that basically says the same thing, a bit more information.
In your mlfnonneg routine, add the following two lines (in a place where they are executed "once per iteration"):
global IT_COUNT;
if numel(IT_COUNT)==0, IT_COUNT = 1; else IT_COUNT = IT_COUNT + 1; end
This ensures that if you forget to create the variable at the top level, the code will not crash (you will thank me in the future, when you re-use this code and don't remember that you need a global variable...)
At the top level, add
global IT_COUNT
IT_COUNT = 0;
Then run your timeit() routine; finally use
fprintf(1, "The number of iterations was %d\n", IT_COUNT);
to get the answer you were looking for.

Best way to add a "forCount" control structure to Objective-C?

Adam Ko has provided a magnificent solution to this question, thanks Adam Ko.
BTW if, like me, you love the c preprocessor (the thing that handles #defines), you may not be aware there is a handy thing in XCode: right click on the body of one of your open source files, go down near the bottom .. "Preprocess". It actually runs the preprocessor, showing you the overall "real deal" of what is going to be compiled. It's great!
This question is a matter of style and code clarity. Consider it similar to questions about subtle naming issues, or the best choice (more readable, more maintainable) among available idioms.
As a matter of course, one uses loops like this:
for(NSUInteger _i=0; _i<20; ++_i)
{
.. do this 20 times ..
}
To be clear, the effect is to to do something N times. (You are not using the index in the body.)
I want to signal clearly for the reader that this is a count-based loop -- ie, the index is irrelevant and algorithmically we are doing something N times.
Hence I want a clean way to do a body N times, with no imperial entanglements or romantic commitments. You could make a macro like this:
#define forCount(N) for(NSUinteger __neverused=0; __neverused<N; ++__neverused)
and that works. Hence,
forCount(20)
{
.. do this 20 times ..
}
However, conceivably the "hidden" variable used there could cause trouble if it collided with something in the future. (Perhaps if you nested the control structure in question, among other problems.)
To be clear efficiency, etc., is not the issue here. There are already a few different control structures (while, do, etc etc) that are actually of course exactly the same thing, but which exist only as a matter of style and to indicate clearly to the reader the intended algorithmic meaning of the code passage in question. "forCount" is another such needed control structure, because "index-irrelevant" count loops are completely basic in any algorithmic programming.
Does anyone know the really, really, REALLY cool solution to this? The #define mentioned is just not satisfying, and you've thrown in a variable name that inevitably someone will step on.
Thanks!
Later...
A couple of people have asked essentially "But why do it?"
Look at the following two code examples:
for ( spaceship = 3; spaceship < 8; ++spaceship )
{
beginWarpEffectForShip( spaceship )
}
forCount( 25 )
{
addARandomComet
}
Of course the effect is utterly and dramatically different for the reader.
After all, there are alresdy numerous (totally identical) control structures in c, where the only difference is style: that is to say, conveying content to the reader.
We all use "non-index-relative" loops ("do something 5 times") every time we touch a keyboard, it's as natural as pie.
So, the #define is an OKish solution, is there a better way to do it? Cheers
You could use blocks for that. For instance,
void forCount(NSUInteger count, void(^block)()) {
for (NSUInteger i = 0; i < count; i++) block();
}
and it could be used like:
forCount(5, ^{
// Do something in the outer loop
forCount(10, ^{
// Do something in the inner loop
});
});
Be warned that if you need to write to variables declared outside the blocks you need to specify the __block storage qualifier.
A better way is to do this to allow nested forCount structure -
#define $_TOKENPASTE(x,y) x##y
#define $$TOKENPASTE(x,y) $_TOKENPASTE(x, y)
#define $itr $$TOKENPASTE($_itr_,__LINE__)
#define forCount(N) for (NSUInteger $itr=0; $itr<N; ++$itr)
Then you can use it like this
forCount(5)
{
forCount(10)
{
printf("Hello, World!\n");
}
}
Edit:
The problem you suggested in your comment can be fixed easily. Simply change the above macro to become
#define $_TOKENPASTE(x,y) x##y
#define $$TOKENPASTE(x,y) $_TOKENPASTE(x, y)
#define UVAR(var) $$TOKENPASTE(var,__LINE__)
#define forCount(N) for (NSUInteger UVAR($itr)=0, UVAR($max)=(NSUInteger)(N); \
UVAR($itr)<UVAR($max); ++UVAR($itr))
What it does is that it reads the value of the expression you give in the parameter of forCount, and use the value to iterate, that way you avoid multiple evaluations.
On possibility would be to use dispatch_apply():
dispatch_apply(25, myQueue, ^(size_t iterationNumber) {
... do stuff ...
});
Note that this supports both concurrent and synchronous execution, depending on whether myQueue is one of the concurrent queues or a serial queue of your own creation.
To be honest, I think you're over addressing a non-issue.
If want to iterate over an entire collection use the Objective-C 2 style iterators, if you only want to iterate a finite number of times just use a standard for loop - the memory space you loose from an otherwise un-used integer is meaningless.
Wrapping such standard approaches up just feels un-necessary and counter-intuitive.
No, there is no cooler solution (not with Apple's GCC version anyways). The level at which C works requires you to explicitly have counters for every task that require counting, and the language defines no way to create new control structures.
Other compilers/versions of GCC have a __COUNTER__ macro that I suppose could somehow be used with preprocessor pasting to create unique identifiers, but I couldn't figure a way to use it to declare identifiers in a useful way.
What's so unclean about declaring a variable in the for and never using it in its body anyways?
FYI You could combine the below code with a define, or write something for the reader to the effect of:
//Assign an integer variable to 0.
int j = 0;
do{
//do something as many times as specified in the while part
}while(++j < 20);
Why not take the name of the variable in the macro? Something like this:
#define forCount(N, name) for(NSUInteger name; name < N; name++)
Then if you wanted to nest your control structures:
forCount(20, i) {
// Do some work.
forCount(100, j) {
// Do more work.
}
}

Constants in MATLAB

I've come into ownership of a bunch of MATLAB code and have noticed a bunch of "magic numbers" scattered about the code. Typically, I like to make those constants in languages like C, Ruby, PHP, etc. When Googling this problem, I found that the "official" way of having constants is to define functions that return the constant value. Seems kludgey, especially because MATLAB can be finicky when allowing more than one function per file.
Is this really the best option?
I'm tempted to use / make something like the C Preprocessor to do this for me. (I found that something called mpp was made by someone else in a similar predicament, but it looks abandoned. The code doesn't compile, and I'm not sure if it would meet my needs.)
Matlab has constants now. The newer (R2008a+) "classdef" style of Matlab OOP lets you define constant class properties. This is probably the best option if you don't require back-compatibility to old Matlabs. (Or, conversely, is a good reason to abandon back-compatibility.)
Define them in a class.
classdef MyConstants
properties (Constant = true)
SECONDS_PER_HOUR = 60*60;
DISTANCE_TO_MOON_KM = 384403;
end
end
Then reference them from any other code using dot-qualification.
>> disp(MyConstants.SECONDS_PER_HOUR)
3600
See the Matlab documentation for "Object-Oriented Programming" under "User Guide" for all the details.
There are a couple minor gotchas. If code accidentally tries to write to a constant, instead of getting an error, it will create a local struct that masks the constants class.
>> MyConstants.SECONDS_PER_HOUR
ans =
3600
>> MyConstants.SECONDS_PER_HOUR = 42
MyConstants =
SECONDS_PER_HOUR: 42
>> whos
Name Size Bytes Class Attributes
MyConstants 1x1 132 struct
ans 1x1 8 double
But the damage is local. And if you want to be thorough, you can protect against it by calling the MyConstants() constructor at the beginning of a function, which forces Matlab to parse it as a class name in that scope. (IMHO this is overkill, but it's there if you want it.)
function broken_constant_use
MyConstants(); % "import" to protect assignment
MyConstants.SECONDS_PER_HOUR = 42 % this bug is a syntax error now
The other gotcha is that classdef properties and methods, especially statics like this, are slow. On my machine, reading this constant is about 100x slower than calling a plain function (22 usec vs. 0.2 usec, see this question). If you're using a constant inside a loop, copy it to a local variable before entering the loop. If for some reason you must use direct access of constants, go with a plain function that returns the value.
For the sake of your sanity, stay away from the preprocessor stuff. Getting that to work inside the Matlab IDE and debugger (which are very useful) would require deep and terrible hacks.
I usually just define a variable with UPPER_CASE and place near the top of the file. But you have to take the responsibly of not changing its value.
Otherwise you can use MATLAB classes to define named constants.
MATLAB doesn't have an exact const equivalent. I recommend NOT using global for constants - for one thing, you need to make sure they are declared everywhere you want to use them. I would create a function that returns the value(s) you want. You might check out this blog post for some ideas.
You might some of these answers How do I create enumerated types in MATLAB? useful. But in short, no there is not a "one-line" way of specifying variables whose value shouldn't change after initial setting in MATLAB.
Any way you do it, it will still be somewhat of a kludge. In past projects, my approach to this was to define all the constants as global variables in one script file, invoke the script at the beginning of program execution to initialize the variables, and include "global MYCONST;" statements at the beginning of any function that needed to use MYCONST. Whether or not this approach is superior to the "official" way of defining a function to return a constant value is a matter of opinion that one could argue either way. Neither way is ideal.
My way of dealing with constants that I want to pass to other functions is to use a struct:
% Define constants
params.PI = 3.1416;
params.SQRT2 = 1.414;
% Call a function which needs one or more of the constants
myFunction( params );
It's not as clean as C header files, but it does the job and avoids MATLAB globals. If you wanted the constants all defined in a separate file (e.g., getConstants.m), that would also be easy:
params = getConstants();
Don't call a constant using myClass.myconst without creating an instance first! Unless speed is not an issue. I was under the impression that the first call to a constant property would create an instance and then all future calls would reference that instance, (Properties with Constant Values), but I no longer believe that to be the case. I created a very basic test function of the form:
tic;
for n = 1:N
a = myObj.field;
end
t = toc;
With classes defined like:
classdef TestObj
properties
field = 10;
end
end
or:
classdef TestHandleObj < handle
properties
field = 10;
end
end
or:
classdef TestConstant
properties (Constant)
field = 10;
end
end
For different cases of objects, handle-objects, nested objects etc (as well as assignment operations). Note that these were all scalars; I didn't investigate arrays, cells or chars. For N = 1,000,000 my results (for total elapsed time) were:
Access(s) Assign(s) Type of object/call
0.0034 0.0042 'myObj.field'
0.0033 0.0042 'myStruct.field'
0.0034 0.0033 'myVar' //Plain old workspace evaluation
0.0033 0.0042 'myNestedObj.obj.field'
0.1581 0.3066 'myHandleObj.field'
0.1694 0.3124 'myNestedHandleObj.handleObj.field'
29.2161 - 'TestConstant.const' //Call directly to class(supposed to be faster)
0.0034 - 'myTestConstant.const' //Create an instance of TestConstant
0.0051 0.0078 'TestObj > methods' //This calls get and set methods that loop internally
0.1574 0.3053 'TestHandleObj > methods' //get and set methods (internal loop)
I also created a Java class and ran a similar test:
12.18 17.53 'jObj.field > in matlab for loop'
0.0043 0.0039 'jObj.get and jObj.set loop N times internally'
The overhead in calling the Java object is high, but within the object, simple access and assign operations happen as fast as regular matlab objects. If you want reference behavior to boot, Java may be the way to go. I did not investigate object calls within nested functions, but I've seen some weird things. Also, the profiler is garbage when it comes to a lot of this stuff, which is why I switched to manually saving the times.
For reference, the Java class used:
public class JtestObj {
public double field = 10;
public double getMe() {
double N = 1000000;
double val = 0;
for (int i = 1; i < N; i++) {
val = this.field;
}
return val;
}
public void setMe(double val) {
double N = 1000000;
for (int i = 1; i < N; i++){
this.field = val;
}
}
}
On a related note, here's a link to a table of NIST constants: ascii table and a matlab function that returns a struct with those listed values: Matlab FileExchange
I use a script with simple constants in capitals and include teh script in other scripts tr=that beed them.
LEFT = 1;
DOWN = 2;
RIGHT = 3; etc.
I do not mind about these being not constant. If I write "LEFT=3" then I wupold be plain stupid and there is no cure against stupidity anyway, so I do not bother.
But I really hate the fact that this method clutters up my workspace with variables that I would never have to inspect. And I also do not like to use sothing like "turn(MyConstants.LEFT)" because this makes longer statements like a zillion chars wide, making my code unreadible.
What I would need is not a variable but a possibility to have real pre-compiler constants. That is: strings that are replaced by values just before executing the code. That is how it should be. A constant should not have to be a variable. It is only meant to make your code more readible and maintainable. MathWorks: PLEASE, PLEASE, PLEASE. It can't be that hard to implement this. . .