Iterating through objects with numbered names - c

I'm actually trying to figured out how i can iterate through some objects in a for loop with names like "Object1, Object2, Object3..."
Here is a code to exemplify what i'm trying to do:
for(int i = 0; i <= numberOfObjects; i++) {
someVariable = Object1.value/Object2.value/Object3.value;
}
In this case in the part of the code that i have the Object1,Object2 and Object3 i will change for something, example Object[i].
In this case it can't be done with arrays since i don't know how much objects were created.

For the C++ language
Put the objects into a std::vector.
Your loop will look like:
for (unsigned int i = 0; i < object_vector.size(); ++i)
{
result = result / object_vector[i].value;
}
For the C language
object my_objects[] = {object1, object2, /*...*/};
array_size = sizeof(my_objects) / sizeof(object);
for (unsigned int i = 0; i < array_size; ++i)
{
result = result / my_objects[i].value;
}

Use an array:
std::vector<T> objects{Object1, Object2, Object3};
for (auto&& x : objects) {
someVariable = x.value;
}
There's no other way to do it.

Related

Need help understanding logic of function

monthly->maxTemperature = yearData[i].high;
monthly->minTemperature = yearData[i].low;
I just can't seem to understand the logic of what the iterations will look like or how to access the proper elements in the array of data to get the proper data for each month.... without corrupting data. Thanks!
You're on the right track:
void stats(int mth, const struct Data yearData[], int size, struct Monthly* monthStats)
{
// These are used to calc averages
int highSum = 0;
int lowSum = 0;
int days = 0;
// Initialize data
monthly->maxTemperature = INT_MIN;
monthly->minTemperature = INT_MAX;
monthly->totalPrecip = 0;
for (int i = 0; i < size; ++i) {
// Only use data from given month
if (yearData[i].month == mth) {
days += 1;
if (yearData[i].high > monthly->maxTemperature) monthly->maxTemperature = yearData[i].high;
if (yearData[i].low < monthly->minTemperature) monthly->minTemperature = yearData[i].low;
highSum += yearData[i].high;
lowSum + yearData[i].low;
monthly->totalPrecip += yearData[i].precip;
}
}
if (0 != days) {
monthly->avgHigh = highSum / days;
monthly->avgLow = lowSum / days;
}
}
Before working on the assignment it's a good idea to examine the API that you need to implement for clues. First thing to notice is that the reason the struct Monthly is passed to your function by pointer is so that you could set the result into it. This is different from the reason for passing struct Data as a pointer*, which is to pass an array using the only mechanism for passing arrays available in C. const qualifier is a strong indication that you must not be trying to modify anything off of the yearData, only the monthStats.
This tells you what to do with the min, max, average, and total that you are going to find in your function: these need to be assigned to fields of monthStats, like this:
monthStats->maxTemperature = maxTemperature;
monthStats->minTemperature = minTemperature;
...
where maxTemperature, minTemperature, and so on are local variables that you declare before entering the for loop.
As far as the for loop goes, your problem is that you ignore the mth variable completely. You need to use its value to decide if an element of yearData should be considered for your computations or not. The simplest way is to add an if to your for loop:
int maxTemperature = INT_MIN; // you need to include <limits.h>
int minTemperature = INT_MAX; // to get definitions of INT_MIN and INT_MAX
for(int i = 0; i<size; ++i) {
if (yearData[i].month < mth) continue;
if (yearData[i].month > mth) break;
... // Do your computations here
}
* Even though it looks like an array, it is still passed as a pointer

MQL4 array creating variables

I'm trying to make this function create X number of variables using an array. I know that this is technically wrong because I need a constant as my array's value (currently 'x'), but excluding that, what am I missing? Looked at so many code samples and can't figure it out, but I know it's got to be simple...
void variables()
{
int i;
int bars = 10;
int x = 1;
for (i = 1; i <= bars+1; i++)
{
int variables[bars] = { x };
x++;
if (i >= bars+1)
{
break;
}
}
void variables()
{
int bars = 10;
if(bars >= Bars) bars = Bars - 1;
// to be able to set array size based on variable,
// make a dynamically sized array
double highvalues[];
ArrayResize(highvalues, bars);
for (int i = 0 /*Note: Array index is zero-based, 0 is first*/; i <= bars; i++)
{
highvalues[i] = iHigh(NULL, 0, i);
// or
highvalues[i] = High[i];
}
}
It is hard to tell what do you want to achieve.
If you want to fill an array with a value ArrayFill() fill help you.

Classification using LibSVM

I am using LibSVM to carry out some multi-class classifications. I trained the model using the MATLAB interface of LibSVM. I then saved this model in a format that would be recognized in C. I now want to classify using svm_predict in C. I am having trouble being able to reproduce the results that I saw in MATLAB. In fact I get the same class output irrespective of what test vector I feed in (even a vector of zeros) I think the issue is with the way I am loading the test vector x into the svm_node structure. Below is the code snippet. Do let me know if this is correct way or if I am missing something.
struct svm_model *libsvm_model = svm_load_model('mymodel.svm');
struct svm_node x[2001]; // this is for one feature vector of size 2000x1
int index = 1;
int i = 0;
for (i = 0; i < features.size(); i++) {
x[i].index = index;
x[i].value = features.at(i);
index = index + 1;
}
x[i+1].index = -1;
x[i+1].value = '?';
double result = svm_predict(libsvm_model, x);
This seems to be a problem:
x[i+1].index = -1;
x[i+1].value = '?';
libsvm requires svm_node to be an input vector, which should have positive indexes, and double values. You should not "leave" some weird empty dimension.
And by the way, you don't need index variable
for (i = 0; i < features.size(); i++) {
x[i].index = index;
x[i].value = features.at(i);
index = index + 1;
}
is equivalent to
for (i = 0; i < features.size(); i++) {
x[i].index = i + 1;
x[i].value = features.at(i);
}

Function Warnings in C

Hello guys i have threefunctions for which i get 4 warnings...!!
The first one is this
void evaluatearxikos(void)
{
int mem;
int i;
double x[NVARS+1];
FILE *controlpointsarxika;
controlpointsarxika = fopen("controlpointsarxika.txt","r");
remove("save.txt");
for(mem = 0; mem < POPSIZE; mem++)
{
for(i = 0; i < NVARS; i++)
{
x[i+1] = population[mem].gene[i];
}
rbsplinearxiki();
XfoilCall();
population[mem].fitness = FileRead();
remove("save.txt");
}
fclose(controlpointsarxika);
}
For this one the compiler warns me tha variable x is set but not used...!! But actually i am using the variable x...!!!
The second function is this one...
void elitist(void)
{
int i;
double best,worst;
int best_mem,worst_mem;
best = population[0].fitness;
worst = population[0].fitness;
for(i = 0; i < POPSIZE - 1; i++)
{
if(population[i].fitness > population[i+1].fitness)
{
if(population[i].fitness >= best)
{
best = population[i].fitness;
best_mem = i;
}
if(population[i+1].fitness <= worst)
{
worst = population[i+1].fitness;
worst_mem = i+1;
}
}
else
{
if(population[i].fitness <= worst)
{
worst = population[i].fitness;
worst_mem = i;
}
if(population[i+1].fitness >= best)
{
best = population[i+1].fitness;
best_mem = i+1;
}
}
}
if(best >= population[POPSIZE].fitness)
{
for(i = 0; i < NVARS; i++)
{
population[POPSIZE].gene[i] = population[best_mem].gene[i];
}
population[POPSIZE].fitness = population[best_mem].fitness;
}
else
{
for(i = 0; i < NVARS; i++)
{
population[worst_mem].gene[i] = population[POPSIZE].gene[i];
}
population[worst_mem].fitness = population[POPSIZE].fitness;
}
}
For this one i get two warnings that the variables worst_mem and best_mem may be used uninitialized in this function..!! But i initialize values to both of them..!!
And the third function is this...
void crossover(void)
{
int mem,one;
int first = 0;
double x;
for(mem =0; mem < POPSIZE; mem++)
{
x = rand()%1000/1000;
if(x < PXOVER)
{
first++;
if(first%2 == 0)
{
random_Xover(one,mem);
}
else
{
one = mem;
}
}
}
}
For which i get that the variable one may be used unitialized..!! But it is initialized..!
Can you please tell me what is wrong with these functions...??
Thank you in advance
In your first function, you set (assign) x, but you never read it, hence you are not using it... you're only wasting CPU cycles by writing to it. (Note also that because you index it as i+1 you write beyond the space you've allocated for it).
In the second function, your initializations to those variables are in conditional blocks. You can see that (perhaps? I didn't verify) in all conditions they are initialized but your compiler isn't that smart.
In your third function, it does appear that one could be refered to without having first been initialized.
First: You set x but do not use it. It's a local variable that gets set but it's dropped as soon as the function returns.
Second: There might be values that makes it so that your best_mem/worst_mem never gets set in your if/else, but you are using them later on. If they haven't been set, they contain garbage if not initialized.
Third: While it shouldn't happen that you try to use an uninitialized variable in your code, it still looks weird and compiler doesn't see that it won't happen first time.
When you get compiler warnings, treat is as you are doing something wrong or rather not recommended and that it could be done in a better way.
The x variable is only used on the left hand side (i.e. assigned a value). You are not using that value on the right hand side or pass it to a function.
It may be possible to get to the end of the loop for(i = 0; i < POPSIZE - 1; i++) without those variables given a value. Why not set them in the declaration.
The call to random_Xover(one,mem); could be called when one is not set. Change the line int mem,one; to int mem,one = <some value>;

How cast array[4] to array[2][2]?

I have a array short frame[4] and I want it as a function parameter as short frame[2][2]
How can I cast it? I tried different things (like *(short [2][2])&frame[0]*), but I still get error messages.
Also not working is if I declare the function with void function(short frame[2][2])
and call the function with function(&frame[0]) while frame is a short frame[4];
I don't think it is a good pratice, anyway:
f((short (*)[2])a);
This works here, albeit with a warning.
#include <stdio.h>
void function(short frame[2][2])
{
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
printf("%d ", frame[i][j]);
printf("\n");
}
int main()
{
short frame[4] = { 0, 1, 2, 3 };
function(&frame[0]);
return 0;
}
What error message do you get?
You can't cast between different dimensional arrays.
It wouldn't know which way round you wanted it.
You'll have to write a function.
In pseudocode:
function castArray(short[4] input){
short[2][2] output = new short[2][2];
output[0][0] = input[0];
output[0][1] = input[1];
output[1][0] = input[2];
output[1][1] = input[3];
return output;
}
You achieve it an easy way like this :
Converting 1-D array into 2-D array
short frame[MAX];
short dup_frame[ROW][COL];
int i,j,k;
for(i = 0 ; i < MAX ; i++)
{
j= i / ROW ; // you can do it by i / COL also
k= i % ROW ; // you can do it by i % COL also
dup_frame[j][k] = frame[i];
}

Resources