getting an error: this statement is incomplete

23 次查看(过去 30 天)
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

采纳的回答

Guillaume
Guillaume 2017-7-22
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 个评论
Image Analyst
Image Analyst 2017-7-22
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.

请先登录,再进行评论。

更多回答(1 个)

John D'Errico
John D'Errico 2017-7-22
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.

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by