C code generated by Matlab Coder has difference results due probable failure of copy on write

3 vues (au cours des 30 derniers jours)
Dear all,
I am trying to convert my Matlab code to C code. The code is a algorithm which at some points copies arrays to compare the values of the next iteration with the arrays of the previous iteration. The original Matlab code takes 10 iteration to converge but the C code converges in only 2 iterations and the results from the C code is wrong. I think the issue lies on the copy on write feature of Matlab. It seems that both copies of the array get assigned the same new values during the second iteration of the algorithm. After that the difference between the new and the old copy is zero and thus the algorithm is terminated. How can I solve this issue? Rewriting the C code to do a deep copy can solve the issue however can I change my Matlab code in someway to solve this issue?
This is the output of the Matlab code:
iteration: 1, crit: 1111.1111
iteration: 2, crit: 10000.0000
iteration: 3, crit: 8888.8889
iteration: 4, crit: 5555.5556
iteration: 5, crit: 3400.0000
iteration: 6, crit: 2266.6667
iteration: 7, crit: 2266.6667
iteration: 8, crit: 1111.1111
iteration: 9, crit: 1111.1111
iteration: 10, crit: 0.0000
This is the output of the C code:
iteration: 1, crit: 200.0000
iteration: 2, crit: 0.0000
A code snippet is below that tries to demonstrate the issue.
nbk = 10; % number of data points in the capital grid
nba = 10; % number of data points in the illiquid capital grid
nbh = 10;
nbz = 4;
kp0 = zeros(nbk,nba,nbh,nbz);
bp0 = zeros(nbk,nba,nbh,nbz);
hp0 = zeros(nbk,nba,nbh,nbz);
kp = zeros(nbk,nba,nbh,nbz);
bp = zeros(nbk,nba,nbh,nbz);
hp = zeros(nbk,nba,nbh,nbz);
crit = 1e6; % convergence criterion
epsi = 1e-6; % convergence parameter
iter = int8(0);
while crit>epsi & iter<100
%%%
%%% New values are assigned to kp, bp, and hp.
%%%
dist = [max(abs(kp-kp0),[],'all'), max(abs(bp-bp0),[],'all'),max(abs(hp-hp0),[],'all')];
crit= max(dist);
kp0 = kp;
bp0 = bp;
hp0 = hp;
end

Réponses (1)

David Fink
David Fink le 1 Mai 2023
MATLAB Coder C code output is expected to match MATLAB results except for expected differences:
Please contact MathWorks Technical Support for assistance.

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Produits


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by