I am new to matlab, and coding is not my job, I just use it for some side projects. So I don't really know what I am talking about, and I hope you'll understand that :)
So I installed matlab on my computer and would like to use its libraries to plot some very simple graphs during the execution of my code (histograms, scatter plots, whatever). Plotting those graphs is not the first purpose of my code, I just find that easier to plot them during the execution rather than exporting them as a CSV file, and then plotting manually through excel.
Question: I managed to make visual C++ "communicate" with matlab. I am passing some data using arrays, but I'd also like to pass a string (a path such as "C:\test\") as I'd like to automatically save those graphs once generated into a precise directory. I haven't found any way of doing it so far.
Here is a bit of my c++ code, which is really simple:
Engine *ep;
ep = engOpen(NULL);
double *ArrayOne;
double *ArrayTwo;
const int Asize = Area.size();
ArrayOne = new double[Asize];
ArrayTwo = new double[Asize];
for (int i = 0; i <= Area.size() - 1; i++) {
ArrayOne[i] = Area[i][1];
ArrayTwo[i] = Area[i][2]
}
mxArray* ONE = mxCreateDoubleMatrix(Asize, 1, mxREAL);
memcpy((void*)mxGetPr(ONE), (void*)ArrayOne, sizeof(double)*Asize);
engPutVariable(ep, "one", ONE);
mxArray* TWO = mxCreateDoubleMatrix(Asize, 1, mxREAL);
memcpy((void*)mxGetPr(TWO), (void*)ArrayTwo, sizeof(double)*Asize);
engPutVariable(ep, "two", TWO);
engEvalString(ep, "plottest");
delete[]ArrayOne;
delete[]ArrayTwo;
engClose(ep);
And the file Plottest.m:
h1= histogram(one);
h1.EdgeColor = 'black';
h1.FaceColor = 'white';
hold on;
h2 = histogram(two);
h2.EdgeColor = 'blue';
h2.FaceColor = [0.5 0.5 0.5];
alpha(h1,.5);
alpha(h2,.8);
saveas(gcf,'C:\PhD\SVG2GMSH\SVG\test.png');
How can I replace my hard coded path into my m file ("C:\PhD\SVG2GMSH\SVG\test.png") by a more elegant variable that would contain it ?
Thank you for your help. Also, let me know if you have any other suggestions in order to make my code look/work better :)
Flo
I don't see what benefit a variable would bring when you'd only need to update the value of the variable anyway.
Your best bet is to use a relative path: saveas(gcf, 'test.png') then the file is taken from the current working directory. The documentation doesn't actually outright state this, but it's basically how computers work, so… give it a go!
Related
I have two questions actually.
I am currently trying to use jpeg() with RMarkdown. It used to work quite well but stopped working and have no idea why. </p>
a. Here is my code:
attach(Hippocampus)
jpeg("Pictures_OnePlot.jpeg", width = 5, height = 3.5, units = "in", res = 600)
plot(Months_as_Taxi_Driver, Anterior_Hippocampus_Volume_mm3,
main = bold("Volume /")~ bold(mm^3) ~ bold("vs Months as a Taxi Driver"),
cex.main = 1.25,
cex.lab = 1,
xlab = "Anterior Hippocampus Volume" ~ (mm^3),
ylab = "Months as Taxi Driver")
graphics.off()
Code
Hippocampus Data
Moreover, now when I try running the code or knitting my file, it does not work at all.
Once the above gets fixed, how do I save this file into a different folder or into a subfolder within the same folder? Before, it would just save it in the same folder as the R-Markdown folder, but I'd like it to go into a sub-folder.
Thanks for the help, everyone. :)
I tried using dev.off() at the end instead and tried Googling with no avail. There was a similar thread though they used x11(), which doesn't work with R (and I am not even sure what x11() is, but that is a different story).
I know how to do the above via ggsave() when I use ggplot, but I'd like to know this method too (especially when using plot().
Thanks again!
I would like to use a convolution LSTM in my research but I'm having a difficult time figuring out the exact way to implement this class in tensorflow. Here is what I have so far. I get no errors, but I am seriously doubting my implementation. Can anyone confirm if I am doing this correctly?
n_input = 4
x = tf.placeholder(tf.float32,shape=[None,n_input,HEIGHT,WIDTH,2])
y = tf.placeholder(tf.float32,shape=[None,HEIGHT,WIDTH,2])
convLSTM_cell = tf.contrib.rnn.ConvLSTMCell(
conv_ndims=2,
input_shape = [HEIGHT,WIDTH,DEPTH],
output_channels=2,
kernel_shape=[3,3]
)
outputs, states = tf.nn.dynamic_rnn(convLSTM_cell, x, dtype=tf.float32)
weights = tf.Variable(tf.random_normal([3,3,2,2]))
biases = tf.Variable(tf.random_normal([2]))
conv_out = tf.nn.conv2d(outputs[-1],weights,strides=[1,1,1,1],padding='SAME')
out = tf.nn.sigmoid(conv_out + biases)
UPDATE:
printing the size of outputs gives the shape=(?,4,436,1024,2) but I think I want (?,5,436,1024,2) or (?,1,436,1024,2).
UPDATE2:
So according to a fellow lab mate, the 4 outputs corresponds to the lstm outputs for each frame and so it is working correctly. Apparently all I have to do is take output #4 and that is the predicted future time frame.
A stackoverflow confirmation would put my mind at ease on this whole thing.
Yes, you are correct!
The output dimension will match the input dimension. If you actually want the (?,5,436,1024,2) output, you will have to look at the history, state.h. the last four [-4] of it will still correspond to the output.
I have a PID controller working in simulink, but I want to pass it to C++ code. I found how to make a PID with code, something like this:
error = input - refeed;
iError += error * sampleTime;
dError = (error - lastError)/ sampleTime;
//PID Function
output = Kp * error + Ki * iError + Kd * dError;
refeed = output;
lastError = error;
But, that's the only clear thing I got in my research.
I need to know what's the next step, I have the transfer function discretized but I'm not sure about what should I do with the "z" parameters, the times, ...
Is it possible to pass manually a PID controller to C++? How?
The Temperature Control Lab passes a PID output from Python to an Arduino that runs C++ code through a serial USB interface. It is easier to plot values with Python than C++ if you can create an interface for your application. GitHub source code is here.
For the digital control systems, you need to sample the data and execute the controller at every sampling time. z-transform converts the continuous system to the discrete system.
For exampl, if your sampling time is '1', you can express a simple time-series model as below,
y(t) = a1*u(t-1) + a2*u(t-2)
--> y(t) = a1*z^-1*u(t) + a2*z^-2*u(t)
--> y(t) = A(z)u(t), where A(z) = a1*z^-1 + a2*z^-2
a1, a2 = FIR coefficients
However, this time-shift operator 'z^-1' does not appear in your code. It is implicitly expressed with your sampling-time and FOR or DO loop depending on the language that you are using.
Please see the python code for velocity form of PID controller. Velocity form is a little bit easier to implement because you don't worry about the additional logic for the anti-reset windup.
for i in range(1, ns): #ns = simulation time
# PID Velocity form
e[i] = sp[i] - pv[i]
P[i] = Kc * (e[i] - e[i-1])
I[i] = Kc*delta_t/tauI * (e[i])
D[i] = Kc*tauD/delta_t * (pv[i] - 2*(pv[i-1]) + pv[i-2])
op[i] = op[i-1] + P[i] + I[i] + D[i]
if op[i] < oplo or op[i] > ophi:
# clip output
op[i] = max(oplo,min(ophi,op[i]))
You can also find an example of a PID controller using a GEKKO package in the following link.
https://apmonitor.com/wiki/index.php/Main/GekkoPythonOptimization
Yes it is possible. Have you considered using someone else's code? Or do you want to write it yourself? If you have no problem using allready written code, check out Github. It has a lot of PID projects. For example PID-controller. It has a usage example and you only have to pass in your p, i and d parameters (which you allready got from Matlab).
Good luck!
Basically, you should send the values somewhere. Reading through the comments, you want to make a plot of the output variable in time, so I guess your best bet (and easier way) is to use gnuplot.
Basically, output the data in a text file, then use gnuplot to display it.
I have a Matlab script that I'm trying to convert to C++ (see below) because it is extremely slow. I'm a C++ newbie and to start I tried using codegen but it doesn't work (I got the message ??? This text contains non-empty top-level expressions. It appears to be a script.)
Do you have any suggestion on how to start to convert the code? Also, what is the best C++ function to do the job of fitsread?
Here is my code:
clear;
number_projections = 10;
imgs_per_proj = 2000; % Number of images per projection
% Lets load the reference images relative to the various wavelengths
R1 = zeros(imgs_per_proj, 512, 512);
R2 = zeros(imgs_per_proj, 512, 512);
l = 0;
for k = 1:imgs_per_proj
s = sprintf('Ref/R1_000_%05i.fits',k-1);
t = sprintf('Ref/R2_000_%05i.fits',k-1);
l = l + 1;
R1(l,:,:) = fitsread(s);
R2(l,:,:) = fitsread(t);
end
codegen requires that the MATLAB code you're trying to convert be in a function and it seems you are trying to convert a script
However, even if you do that, fitsread does not appear to be a supported function within codegen. Here's a list of supported functions:
http://www.mathworks.com/help/simulink/ug/functions-supported-for-code-generation--alphabetical-list.html
There's no "built-in" function within C++ that's going to replace fitsread - for that you need a library. There's a C++ FITS library called CCFits that you can find here: http://heasarc.gsfc.nasa.gov/fitsio/CCfits/
They should have tutorials that you could follow.
I'm programming a Steinberg VST-Plugin in XCode 4.6.
I've already implemented a Highpass-filter which works correctly. Now I'm trying to do some nonlinear distortion with a quadratic function. After I implemented the few lines below and loaded the plugin into the host, I get immediatly an Output from the plugin - you can hear nothing, but the meter is up high.
I really can't imagine why. The processReplacing function where the math takes place should only be called when playing sound, not when the plugin is loaded. When I remove the few lines of code below, everything is okay and sounds right, so I assume it has nothing to do with the rest of the plugin-code.
The problem takes place in two hosts, so its probably not a VST-bug.
Has anybody ever experienced a similar problem?
Many Thanks,
Fabian
void Exciter::processReplacing(float** inputs, float** outputs, VstInt32 sampleFrames){
for(int i = 0; i < sampleFrames; i++) {
tempsample = inputs[0][i];
//Exciter - Transformation in positive region, quadratic distortion and backscaling
tempsample = tempsample + 1.0f;
tempsample = powf(tempsample, 2.0f);
tempsample = tempsample / 2.0f;
tempsample -= 1.0f;
//Mix-Knob: Dry/Wet ------------------------------------------------
outputs[0][i] = mix*(tempsample) + (1-mix)*inputs[0][i];
EDIT: I added logfile-outputs to each function and it occurs, that the processReplacing function is called permanently, not only when playback is turned on ... But why?
You pretty much answered the question yourself with your edit. processReplacing is called repeatedly. This is part of the VST specification.
VST plug-ins are targeted for real time effects processing. Don't confuse or misinterpret this as lookahead. By real time, I mean inserting the plug-in into a channel and playing an instrument while the DAW is recording. So you can see that in order to mitigate latency, the host is always sending the plug-in an audio buffer (whether it's silence or not).