How to set the initial value for C caller block?

3 次查看(过去 30 天)
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 个评论
Walter Roberson
Walter Roberson 2023-9-5
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;
}

请先登录,再进行评论。

回答(1 个)

Riya
Riya 2023-9-5
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 initializedis 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!

类别

Help CenterFile Exchange 中查找有关 General Applications 的更多信息

标签

产品


版本

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by