Accessing struct by variable in Code Generation

조회 수: 6 (최근 30일)
Matt Schramm
Matt Schramm 2020년 12월 13일
댓글: Matt Schramm 2020년 12월 15일
Hello,
I am trying to use code generator to accelerate a text reader for my research. I am currently stuck at the following lines.
curLine = fgetl(fid);
atts = strsplit_c(curLine,' ');
for m = 3:length(atts)
data.(atts{m}) = zeros(real(data.numAtoms),1);
end
The error occures at "data.(atts{m}) = zeros(real(data.numAtoms),1);" with the error "Non-constant expression or empty matrix. This expression must be constant because its value determines the size or class of some expression".
strsplit_c is my implementation of strsplit that is code generation happy. If this may be the location of the error I will be happy to post that code.
I have a second error where I try to place values in the structure.
line = fgetl(fid);
lineVal = eval_c(line,' ');
% lineVal = eval(['[',line,']']);
for m = 3:length(atts)
data.(atts{m})(k) = lineVal(m-2); % <- This is where the error is...
end

답변 (1개)

Walter Roberson
Walter Roberson 2020년 12월 14일
I suspect that your first problem is not the dynamic field name, but rather the dynamic size of the array being generated. MATLAB needs to know the size because it needs to generate the array on the stack, and it needs to be sure that it is not going to overrun the allocated stack space.
The work-around is to use coder.varsize https://www.mathworks.com/help/coder/ref/coder.varsize.html
This allows variables to be allocated on the heap instead of on the stack.
I think you might still have problems with dynamic field names, but you could test that part out separately by experimenting with assigning something of constant size instead of dynamic size.
  댓글 수: 9
Matt Schramm
Matt Schramm 2020년 12월 15일
I'll try the fopen and simply pass the fid.
I tried building the entire file name before sending it to the function but was met with the error that the char array changed sizes and you can't use coder.varsize on an input value.
Matt Schramm
Matt Schramm 2020년 12월 15일
Passing the fid worked.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Call C from MATLAB에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by