Sum two values coming from eval

3 次查看(过去 30 天)
Hi,
I would like to ask how to sum two numerical values, which coming from the eval fucntion
set(handles.A_edit,'string',eval(char(strcat('handles.forces.',gridnames(gridnum,1),'.total.B_IBE'))));
+
set(handles.A_edit,'string',eval(char(strcat('handles.forces.',gridnames(gridnum,1),'.total.C_IBE'))));
  3 个评论
Davide Di Pasquale
Davide Di Pasquale 2018-12-10
Hi KSSV,
just picked up an existing code that used this eval function.
I have just to sum two force component.
Regards
Stephen23
Stephen23 2018-12-10
编辑:Stephen23 2018-12-10
"just picked up an existing code that used this eval function."
For more than ten years it has been recommended to avoid using eval to dynamically access structure fieldnames, since MATLAB 6.5:
So whoever wrote that code is badly informed and uses poor programming practices. Do NOT learn from that code!

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2018-12-10
Plenty of problems with your code.
For a start set as you use it does not return a value, so there is nothing to sum. I'm going to assume that's the output of eval you want to sum. Nothing is stopping you to sum these output before you call set.
2nd problem: Can the B_IDE ad C_IBE be summed? For that they would need to be numeric. But the string property of uicontrol expects text. Perhaps the sum should be converted to text, but you don't show that.
3rd problem: I don't see the point of the char. strcat already outputs a char array. Unless gridnames is a cell array of course, but in that case, clearly you don't know how to extract values from a cell array (using {}). In that case,
char(strcat('handles.forces.',gridnames(gridnum,1),'.total.B_IBE'))
should be:
strcat('handles.forces.',gridnames{gridnum,1},'.total.B_IBE') %and if gridnames is a vector cell array 2d indexing is a waste of time.
And of course, 4th problem is the use of eval. It's completely unnecessary as well here as there's much simpler syntax to obtain the same.
In the end, I'm going to guess that what you want to do is:
B_total = handles.forces.(gridnames{gridnum}).total.B_ICE;
C_total = handles.forces.(gridnames{gridnum}).total.C_ICE;
set(handles.A_edit, 'string', num2str(B_total + C_total))
  4 个评论
Stephen23
Stephen23 2019-1-30
Davide Di Pasquale's "Answer" moved here:
Hi Guillaume,
Now the problem is solved:
B_total = strcat(handles.forces.(gridnames{gridnum}).total.VISCOUSDRAG_TE);
C_total = strcat(handles.forces.(gridnames{gridnum}).total.CD_vortd);
set(handles.cd_edit, 'string', num2str(str2double(B_total)+ str2double(C_total)));
Thanks
Stephen23
Stephen23 2019-1-30
@Davide Di Pasquale: I accepted Guillaume's answer on your behalf, as you indicated that this answer helped you to resolve your question.

请先登录,再进行评论。

更多回答(0 个)

类别

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

标签

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by