#include <stdio.h>
#include <math.h>
int iii;
double E_[100], t_[100], length, lowest_temp, acceptance;
int main(int argc, char *argv[]) {
length=(double)20;
lowest_temp=(double)0.20; /* setting lowest temperature */
acceptance=(double)0.50; /* Acceptance i--> j */
E_[10]=(double)1.3; /*starting E */
t_[0]=lowest_temp;
for(iii>=11;iii<=length-1;iii++){/*CB2*/
E_[10]=1.3;
E_[iii]=E_[iii-1]+(E_[iii-1]/10);
/*Can change 10 to other percentage or random number */
printf("E_[%i]=%f\n",iii,E_[iii]);
}/*CB2*/
for(iii<=9;iii>=0;iii--){/*CB3*/
E_[10]=1.3;
E_[iii]=E_[iii+1]-(E_[iii+1]/10);
printf("E_[%i]=%f\n",iii,E_[iii]);
}/*CB3*/
for(iii=0;iii<=length-1;iii++){/*CB4*/
t_[iii+1]=-((int)1/(t_[iii]))-(log(acceptance)/(E_[iii]+E_[iii+1]));
printf("t_[%i]=%f\n",iii,t_[iii]);
}/*CB4*/
When I run the code I get the following print out:
E_[0]=0.000000
E_[1]=0.000000
E_[2]=0.000000
E_[3]=0.000000
E_[4]=0.000000
E_[5]=0.000000
E_[6]=0.000000
E_[7]=0.000000
E_[8]=0.000000
E_[9]=0.000000
E_[10]=0.000000
E_[11]=1.430000
E_[12]=1.573000
E_[13]=1.730300
E_[14]=1.903330
E_[15]=2.093663
E_[16]=2.303029
E_[17]=2.533332
E_[18]=2.786665
E_[19]=3.065332
E_[20]=0.000000
E_[19]=0.000000
E_[18]=0.000000
E_[17]=0.000000
E_[16]=0.000000
E_[15]=0.000000
E_[14]=0.000000
E_[13]=0.000000
E_[12]=0.000000
E_[11]=0.000000
E_[10]=0.000000
E_[9]=1.170000
E_[8]=1.053000
E_[7]=0.947700
E_[6]=0.852930
E_[5]=0.767637
E_[4]=0.690873
E_[3]=0.621786
E_[2]=0.559607
E_[1]=0.503647
E_[0]=0.453282
t_[0]=0.200000
t_[1]=-4.275654
t_[2]=0.885794
t_[3]=-0.542211
t_[4]=2.372348
t_[5]=0.053720
t_[6]=-18.187354
t_[7]=0.439930
t_[8]=-1.926635
t_[9]=0.830847
t_[10]=-0.922965
t_[11]=1.616655
t_[12]=inf
t_[13]=inf
t_[14]=inf
t_[15]=inf
t_[16]=inf
t_[17]=inf
t_[18]=inf
t_[19]=inf
My objective is to populate the t_[iii] array using the computed E_[iii] array. In order to generate the E_[iii] array I take a pre-existing E_[iii] value from elsewhere in the code (1.3 in this case), then either side of this create for E_[iii>10] values greater than E_[10] and correspondingly below create for E_[iii<10] values less than E_[10].
Arbitrarily I set this to ten percent lower for adjacent E values. Using this I successfully generate the correct values either side of E_[10] however I cannot generate them within the same loop and it seems to be resetting the unused iii indices to zero as can be seen from the print outs.
I would very much appreciate any help in this issue!
One problem: for-loop initialisation. At CB2 and CB3, the iii>=11 and iii<=9 expressions don't initialise iii.
Related
I am making a Rcpp code for Gibbs sampling. Inside the code, I first want to make a 3 dimensional array with row number= number of iteration (500), column number=number of parameter(4) and slice number= number of chain(3). I wrote it in this way:
#include <RcppArmadillo.h>
#include <math.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace std;
using namespace arma;
//Gibbs sampling code starts here
Rcpp::List mcmc(const int iter,const int chains, const NumericVector data){
arma::cube posteriorC = arma::zeros(iter, 5, chains);
\\ rest of the codes
List out(Rcpp::List::create(Rcpp::Named("posteriorC") =posteriorC));
return out;
}
. While compelling it does not show any error. But when I want to run the code with:
res<- mcmc(iter=500,chains=2,data)
it shows the error:
Error: Cube::operator(): index out of bounds
. I want to know if there any mistake while making the 3D array. Please note that I want to get estimates of 5 parameters of my model.
You need to specify the template for arma::zeros to correctly fill an arma::cube, c.f. arma::zeros<template>
Generate a vector, matrix or cube with the elements set to zero
Usage:
vector_type v = zeros<vector_type>( n_elem )
matrix_type X = zeros<matrix_type>( n_rows, n_cols )
matrix_type Y = zeros<matrix_type>( size(X) )
cube_type Q = zeros<cube_type>( n_rows, n_cols, n_slices )
cube_type R = zeros<cube_type>( size(Q) )
Thus, in your case it would be:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
Rcpp::List mcmc(const int iter, const int chains,
const Rcpp::NumericVector data){
arma::cube posteriorC = arma::zeros<arma::cube>(iter, 5, chains);
// --------------------------------- ^^^^^^^^
// Not Shown
Rcpp::List out = Rcpp::List::create(Rcpp::Named("posteriorC") =posteriorC);
return out;
}
Two final notes:
You explicitly state that the code as it stands now will create 4 columns to store 4 variables. However, you explicitly mention that you needed to estimate 5 parameters. You may need to increase this to prevent an out of bounds when saving into the arma::cube slices.
The way the Rcpp::List out is being created isn't quite correct. In general, the best way to create the list is to do: Rcpp::List out = Rcpp::List::create(Rcpp::Named("Blah"), Blah);
I've got some code which generates an array of strings of different file names and then
passes them into a function to write some data to them. It adds a incrementing number to the starting filename which is supplied from an input argument.
The problem is that it works fine running from source in Visual Studio 2012 but when I compile it and run it as an .exe the program crashes.
The .exe doesn't appear to be passing the array of strings properly which is causing an error when it attempts to use the string
for opening a file etc.
Here is the isolated bit of code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
#include <stdint.h>
#include <Windows.h>
void processing_function(int num_output, char **outnames)
{
/* in Visual Studio this works fine and prints all
the names correctly. Running from .exe will crash */
for(int idx = 0; idx <num_output;idx++)
{
printf("outnames[%d] is %s\n",idx,outnames[idx]);
}
}
int main(int argc, char *argv[])
{
/*nframes comes from another function, outname comes from input arguement */
int num_output = ceil(((double)*nframes / 1100));
int outname_len = strlen(outname)+1;
char *out_right;
out_right = (char*) malloc(sizeof(char)*outname_len);
/*Split string to append numbers before file extension */
strcpy(out_right,outname);
strrev(out_right);
strtok(out_right,".");
strcat(out_right,".");
strrev(out_right);
int out_right_len = strlen(out_right);
strtok(outname,".");
strcat(outname,"-");
int out_origlen = strlen(outname);
int num_len = 1;
char **outnames;
char *num;
char *outname_tmp;
outnames = (char**) malloc(sizeof(char)*(num_output));
int out_len;
double dbl_idx;
int *numfs = (int*)malloc(sizeof(int)*num_output);
for(int idx = 1;idx <num_output+1;idx++)
{
/*convert output number to string and stitch complete name back together and place into array */
num_len = ceil(log10((double)idx+0.1));
num = (char*) malloc(sizeof(char)*(num_len+1));
outname_tmp = (char*) malloc(sizeof(char)*(out_origlen+num_len+out_right_len+1));
strcpy(outname_tmp,outname);
sprintf(num,"%d",idx);
strcat(outname_tmp,num);
free(num);
strcat(outname_tmp,out_right);
outnames[idx-1] = (char*) malloc(sizeof(char)*(out_origlen+num_len+out_right_len+1));
strcpy(outnames[idx-1],outname_tmp);
free(outname_tmp);
printf("%s\n",outnames[idx-1]);
}
free(out_right);
processing_function(num_ouput, outnames)
return(0);
}
EDIT: Changed num_input to num_output as they do have the same value.
Running from .exe will sometimes start printing some of the names and then crash, opening the
debugger gives an error within output.c, with an access reading violation. I tried putting this code at
the top of the processing_function but that gave further problems downstream (heap corruption), which makes me think that the
code is messing up the memory but I can't see whats wrong with it, nor why it would work in VS but not as a .exe.
I could try and dodge the issue by generating the next output name on the fly every time it requires one but I'd really rather know why this isn't working.
Any help would be greatly appreciated.
I am going to take a shot and say, you passed num_input to processing_function() with outnames, outnames was allocated with num_output for size, but num_input and num_output have different values at runtime. So that lets processing_function() access out of bounds.
This is my one dimensional array A, containing 10 numbers:
A = [-8.92100000000000 10.6100000000000 1.33300000000000 ...
-2.57400000000000 -4.52700000000000 9.63300000000000 ...
4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000];
I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8
(a(1)+a(2))/2 - value stored in one block of a matrix say m= zeros(10)
then (a(1)+a(2)+a(3)+a(4))/4 ------ mean-----
then (a(1)+a(2)..... a(8))/8
Then shift indexes:
(a(2)+a(3))/2; - mean
(a(2)+a(3)+a(4)+a(5))/4
(a(2)+a(3)...a(9))/8
SO basically 2^n length interval
%____ my code _____%
A= newArrayy;
sum=0;
storeD = zeros(3,9);
flag=true;
for k=1:9
n=1;
while(true)
if(k+(2^n-1)<10)
meanSum= mean(A(k):A(k+2^n-1))
storeD(n,k)= meanSum;
n=n+1;
else
flag=false;
end
end
end
I need to find standard deviation, covariance and mean for each interval, but I get an error on the meanSum line.
In the meanSum line, you should write
A(k:k+2^n-1)
You want to access the elements ranging from k to k+2^n-1. Therefore you have to provide the range to the selection operation.
A few suggestions:
Use a search engine or a knowlegde base to gather information on the error message you received.
Try to understand which operation failed, and how it should work in principle (in your case: the colon operator, e.g. http://de.mathworks.com/help/matlab/ref/colon.html)
If your own efforts don't lead to success, at least post the error message you get to make the question more clear. Better yet, provide a minimal working example. In your case one or two lines of code would suffice.
A = [-8.92100000000000 10.6100000000000 1.33300000000000 ...
-2.57400000000000 -4.52700000000000 9.63300000000000 ...
4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000];
sum=0;
storeD = zeros(3,9);
for k=1:9
n=1;
while(1==1)
if(k+(2^n-1)<=10)
meanSum= mean(A(k:k+2^n-1));
storedD(n,k)= meanSum
covVar= cov(A(k:k+2^n-1));
storedC(n,k)= covVar
stdDev= std(A(k:k+2^n-1));
storedS(n,k)= stdDev
n=n+1;
else
break;
end
end
end
So this worked :D Thanks for the help! There was an error in while loop as i didn't use a break to exit the loop.
Recently, I tried to write mexfunctions using structure variables.
I watched the tutorial but got confused because of how the variable values are passed.
The following example (mexfunction_using_ex_wrong.m & mexfunction_using_ex_wrong.cpp) demonstrates how to fetch the variables passed from matlab in mexfunction.
However, in this case, the result is:
address i_c1=2067094464 i_c2=2067094464
i_c1=10 i_c2=10
address i_c1=1327990656 i_c2=2067100736
i_c1=2 i_c2=20
address i_c1=2067101056 i_c2=2067063424
i_c1=3 i_c2=30
As can be seen, the 1st element of the c1 & c2 array of a structure variable is accidentally the same.
But, in another example (mexfunction_using_ex_correct.m & mexfunction_using_ex_correct.cpp), the elements of array 1 (b1) and array 2(b2) of a structure variable are unrelated as I expect.
The result is:
address i_b1=1978456576 i_b2=1326968576
i_b1=1 i_b2=10
address i_b1=1978456584 i_b2=1326968584
i_b1=2 i_b2=20
address i_b1=1978456592 i_b2=1326968592
i_b1=3 i_b2=30
However, it's more common to use the 1st example in programming. so could anybody explain why in the 1st example the addresses of i_c1 & i_c2 are the same?
The following code is mexfunction_using_ex_wrong.m
clc
clear all
close all
mex mexfunction_using_ex_c_wrong.cpp;
a.b(1).c1=double(1);
a.b(2).c1=double(2);
a.b(3).c1=double(3);
a.b(1).c2=double(1);
a.b(2).c2=double(2);
a.b(3).c2=double(3);
mexfunction_using_ex_c_wrong(a);
The following code is mexfunction_using_ex_c_wrong.cpp
#include "mex.h"
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
int i, j, k;
double *i_c1;
double *i_c2;
// for struct variables(pointers) inside fcwcontext
mxArray *mx_b, *mx_c1, *mx_c2;
mx_b=mxGetField(prhs[0], 0, "b");
for(i = 0;i < 3;i=i+1)
{
mx_c1=mxGetField(mx_b, i, "c1");
mx_c2=mxGetField(mx_b, i, "c2");
i_c1=mxGetPr(mx_c1);
i_c2=mxGetPr(mx_c2);
*i_c2=(*i_c2)*10;
printf("address i_c1=%d i_c2=%d\n", i_c1, i_c2);
printf(" i_c1=%g i_c2=%g\n", *i_c1, *i_c2);
}
}
The following code is mexfunction_using_ex_c_correct.m
clc
clear all
close all
mex mexfunction_using_ex_correct.cpp;
a.b1(1)=double(1);
a.b1(2)=double(2);
a.b1(3)=double(3);
a.b2(1)=double(1);
a.b2(2)=double(2);
a.b2(3)=double(3);
mexfunction_using_ex_correct(a);
The following code is mexfunction_using_ex_c_correct.cpp
#include "mex.h"
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
int i, j, k;
double *i_b1;
double *i_b2;
mxArray *mx_b1, *mx_b2;
mx_b1=mxGetField(prhs[0], 0, "b1");
mx_b2=mxGetField(prhs[0], 0, "b2");
for(i = 0;i < 3;i=i+1)
{
i_b1=mxGetPr(mx_b1);
i_b2=mxGetPr(mx_b2);
i_b2[i]=i_b2[i]*10;
printf("address i_b1=%d i_b2=%d\n", &i_b1[i], &i_b2[i]);
printf(" i_b1=%g i_b2=%g\n", i_b1[i], i_b2[i]);
}
}
The addresses are not "accidentally the same" - they're intentionally the same, due to MATLAB's internal copy-on-write optimisations. If you look at the MEX documentation, you'll see warnings scattered around...
Do not modify any prhs values in your MEX-file. Changing the data in these read-only mxArrays can produce undesired side effects.
...in various forms...
Note Inputs to a MEX-file are constant read-only mxArrays. Do not modify the inputs. Using mxSetCell* or mxSetField* functions to modify the cells or fields of a MATLABĀ® argument causes unpredictable results.
...trying to make it very clear that you should absolutely not modify anything you recieve as an input. By calling mxGetPr() on input data and writing back to that pointer as you do with i_b2 and i_c2, you're getting right into that "unpredictable results" territory - if you look at a.b(1).c1 in the MATLAB workspace after the call, it'll really be 10 even though you "only" changed c2.
From MEX, you're looking at the raw data storage without any knowledge of, or access to, MATLAB's internal housekeeping, so the only safe way to modify anything is to use the mxCreate* or mxDuplicate* functions to get your own safe arrays you can then do whatever you want with, and pass back to MATLAB via plhs.
That said, I will admit to having abused in-place modification for a significant performance gain in one instance where I could guarantee my data was unique and unshared, but it's at best unsupported and at worst downright perilous.
Is there a way to get the line number a function was called on in C without doing anything like below?
The define can make it tedious after a while, having to use DP instead of { like usual, and hard to read; but the adding LINE as the first parameter to every function is just something I'm not willing to do.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#define println(x,...) printf(x,##__VA_ARGS__);printf("\n");
/*
*I would like to be able to replace __LINE__ with the line
*each function was called on, or replace my DP define completely...
*/
#ifdef _DEBUG_
#define DP { println("%s:%d\t%s()",__FILE__,__LINE__,__FUNCTION__);
#else
#define DP {
#endif
void calledFunc()
DP
println("something something something");
}
void cFunc(int line)
{
println("%s:%d\t%s()",__FILE__,line,__FUNCTION__);
}
int main()
DP
calledFunc();
/* ...and I don't want to have to do this all the time either*/
cFunc(__LINE__);
}
There is a good substitute for printing the line file name/number. It is called "LocationID" or LID.
LID is a number that is generated out the project wide counter. The latest value of the counter should be stored in the source file and checked in/out of the source control system like any other source file. The value of the counter can be scrambled. This forces its proper use. You use it like:
#ifdef _DEBUG_
#define DP(x, msg) println("%d: %s", x, msg);
#endif
and in your source:
DP (3517, "Here we are.")
Advantage of the LIDs are:
They are stable against modification of the source file, including renaming of the file/function.
They are easy to find in the sources.
Log file is much more compact and clear than with the file name and the function name.
I used this several times and it proved to be good. Generation and distribution of LID values among developers is an overhead, but the result is 10 times worth the price of this effort.