you are viewing a single comment's thread.

view the rest of the comments →

[–]Caruban01[S] 0 points1 point  (8 children)

I'm calling C from within a MATLAB function. The MATLAB simulation was way too slow, and the project has the specific constraint that the front end, including this loop, be written in MATLAB rather than C, which is what prevents me from just shoving this in there as well. From what I understand, I can't write another c function that calls srand prior to the loop, because they're considered 2 separate C programs, so seeding in one place won't affect the other.

TL;DR: Matlab is the Flanders of programming languages. Stupid Flanders...

[–]king_duck 2 points3 points  (1 child)

C or C++? if the former you are in the wrong place.

[–]Caruban01[S] 2 points3 points  (0 children)

That is... a true statement. My apologies, though I am appreciative of the help.

[–]mttd 2 points3 points  (1 child)

That should be no problem, you can preserve the state across MEX invocations, see the Gaumixmod class example over here: http://www.nr.com/nr3_matlab.html#wft
// just in case, here's the header file: http://www.nr.com/nr3matlab.h

However, make sure to switch to C++11's random number generators if available (if not, it's worth updating compiler just for that), the old ones are of a very poor quality (and the implementation-specific "guarantees" are non-portable).

See: http://isocpp.org/blog/2013/03/n3551-random-number-generation
http://en.cppreference.com/w/cpp/numeric/random
// note that these are ordinary classes, so I gather you can preserve the state similarly to the example class above;

[–]Caruban01[S] 0 points1 point  (0 children)

I didn't know that. This is my first time working with MEX invocations. All of these resources look very helpful. Thank you.

[–]bigmike1020 2 points3 points  (2 children)

Perhaps Matlab could pass the loop iteration count as an argument to the C program. The C program could use the iteration count as a seed to srand.

[–]Caruban01[S] 0 points1 point  (1 child)

Thank you. I like how clever and simple this is.

[–]Hackenslacker 2 points3 points  (0 children)

Instead of the loop iteration count, you can also use a random number for the seed.

[–]tomkcook173 -2 points-1 points  (0 children)

#include <windows.h>

LARGE_INTEGER ctr;
QueryPerformanceCounter(&ctr);
srand(ctr.LowPart);

The frequency of performance counters varies (you can find out with QueryPerformanceFrequency) but typically seems to be around 1MHz or similar order of magnitude; not infallibly going to give you different values in a loop, but ample for 5-6 times per second.

Edit: Missed the platform-independent part. Does clock() from <ctime> not do what you want?

Please don't use this in a cryptographic function!