How to set the initial value for C caller block?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi, I'm using C caller blocks to simulate my C code in simulink.
There is a variable which updates its state with its previous value.(It works the same as integral term in PID controller) The code is below.
void GetVar(double a, double* res)
{
res = res+a;
}
To do this, I need to set the initial value of res, however, I don't know how to set the initial value.
Thanks.
1 comentario
Walter Roberson
el 5 de Sept. de 2023
That code does not update a state. That code takes the value of a and adds sizeof(double) times a bytes to the pointer address stored in res storing the result (locally) in res with nothing outside the routine getting updated.
Were you thinking of code more like
void GetVar(double a, double* res)
{
*res = *res+a;
}
Respuestas (1)
Riya
el 5 de Sept. de 2023
Hello lim daehee,
As per my understanding, the initial value of the variable ‘res’ in your C code is to be set.
In this case, you can modify the code as follows:
void GetVar(double a, double* res)
{
static double initial_value = 0.0; // Set the initial value here
static int initialized = 0; // Flag to check if the initial value is set
if (!initialized)
{
*res = initial_value;
initialized = 1;
}
*res = *res + a;
}
In the modified code, we introduce a ‘static’ variable ‘initial_value’ to hold the initial value of ‘res’. By default, ‘initial_value’ is set to 0.0, but you can change it to any desired initial value.
Additionally, we introduce a ‘static’ flag variable initialized to ensure that the initial value is set only once. The first time ‘GetVar’ is called, it checks if ‘initialized’ is 0. If it is, the initial value is assigned to ‘res’, and initialized is set to 1 to indicate that the initial value has been set.
By using this approach, the initial value of ‘res’ will be set only once, and subsequent calls to ‘GetVar’ will update ‘res’ based on its previous value.
In case you further require a more specific solution tailored to your case, you can provide more information.
You can also refer the following documentation about how to initialize static variable in C caller blocks during simulation for more details:
I hope it helps!
0 comentarios
Ver también
Categorías
Más información sobre General Applications en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!