Argument to dynamic structure reference must evaluate to a valid field name

Here is a code snippet that results in the error message recorded in my question. The program passes the if clause that starts
if isfield...
but baulks (North America: balks) at the next line. I hope that it is obvious to a human reader what I am trying to do. How do I make it obvious to Matlab? Have I given enough info so that someone can help me? I would be happy to give more if required.
for fldn={'raw','scl','svd','pft'}
if isfield(R,(fldn))
err = X*(R.(fldn).coef - Y);
R.(fldn).err = num2cell(mean(err.^2));
end
end
Here are some answers given by the Matlab debugger:
fldn
ans='raw'
R.fldn;
Reference to a non-existent field
R.(fldn);
Argument to dynamic structure reference must evaluate to a valid field name.
R.raw
ans=coef: {[21x1 double]}

 채택된 답변

Display the contents of fldn as well as the class of fldn on the line immediately after the start of the for loop.
mystruct.('abc') = 1 % valid dynamic field name
mystruct.({'def'}) = 2; % NOT a valid dynamic field name
If you want to use fldn as a dynamic field name, you need to extract the char array inside the cell.
x = {'ghi'};
mystruct.(x{1}) = 3;

댓글 수: 1

To expand on this: when you use
for fldn={'raw','scl','svd','pft'}
then for iterates over the columns of the resulting array, and because it is a cell array, each of the columns is a cell array. Your loop variable is not going to be set to strings in turn: it is going to be set to cell arrays that happen to contain one element that is a string.
If you had had
for fldn = {'raw', 'scl'; 'svd', 'pft'}
then because for iterates over columns, the variable would first be set to {'raw'; 'svd'} and then to {'scl' ; 'pft'} .
It does not do what one might prefer, but it is consistent behavior.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Debugging and Improving Code에 대해 자세히 알아보기

질문:

2016년 6월 26일

댓글:

2016년 6월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by