MATLAB Answers

0

getting an error: this statement is incomplete

Asked by Ramis Rafay on 22 Jul 2017
Latest activity Commented on by Image Analyst
on 22 Jul 2017
Ive been getting this error for the 'eval' line and i'm not sure in what way the statement is incomplete.
% Giving initial values vector (element for each layer) of each state variable.
for i=1:length(R(idR).St.StNames),
eval(strcat('R.St.', char(R(idR).St.StNames(i,:)),' = ', char(R(idR).StM(i,:))));
end

  0 Comments

Sign in to comment.

Tags

2 Answers

Answer by Guillaume
on 22 Jul 2017
 Accepted Answer

Important rule: Never use eval
And certainly not for generating dynamic fields when there is a more readable, lots easier to debug, alternative
Also a lot easier to debug: sprintf or, in recent versions, compose instead of concatenating bits of strings together.
Another issue is that it would appear that StNames is 2D (since you have written StNames(i, :)), yet you use length on it which will either return the number of rows or columns, whichever is greater. It's also not clear why it is converted to char.
One more potential problem, you're indexing R everywhere but in strcat('R.St.'. This is clearly not going to work. This is why we say not to use eval. You can't debug that line, and you get not help from the editor.
Not knowing what's in StNames, a guess of a fix:
for row = 1:size(R(idR).St.StNames, 1)
R(idR).St.(char(R(idR).St.StNames(row, :)) = char(R.(idR).StM(row, :);
end
Those char conversion are very suspicious though. Even if the above works, there's probably a much clearer way to write it.
I would also recommend that you use longer names for your fields, ones that have meaning. Finally, I would avoid mixing case as you have. It's a pain to write.

  1 Comment

Also note Guillaume got rid of the comma at the end of the for line. In a test I did, that comma causes an error.

Sign in to comment.


Answer by John D'Errico
on 22 Jul 2017

A textbook reason why it is a bad idea to create variable names on the fly. It creates code that is nasty to debug. The code will be slow, and it will be ugly unreadable stuff like this.
If you will write godawful stuff like this, then you need to learn to debug your code.
In the debugger, step in to see what those variables contain at that point. You will probably find that the line you are trying to execute (as it was created) is not correct MATLAB syntax.

  0 Comments

Sign in to comment.