# Sum two values coming from eval

3 views (last 30 days)
Davide Di Pasquale on 10 Dec 2018
Commented: Stephen23 on 30 Jan 2019
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 CommentsShow 1 older commentHide 1 older comment
Davide Di Pasquale on 10 Dec 2018
Hi KSSV,
just picked up an existing code that used this eval function.
I have just to sum two force component.
Regards
Stephen23 on 10 Dec 2018
Edited: Stephen23 on 10 Dec 2018
"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 on 10 Dec 2018
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))
Stephen23 on 30 Jan 2019
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 on 30 Jan 2019

### Categories

Find more on Whos in Help Center and File Exchange

R2017a

### Community Treasure Hunt

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

Start Hunting!