Filter löschen
Filter löschen

how to use string within a line of code

4 Ansichten (letzte 30 Tage)
Peng Zhao
Peng Zhao am 1 Sep. 2017
Kommentiert: Adam am 1 Sep. 2017
I was trying to use a string as a object handle within a for loop to save space as following:
function pushbutton1_Callback(hObject, eventdata, handles)
for Button = 1
Button = num2str(Button);
Obj = strcat('handles.Num',Button);
set(str2func(Obj), 'ForegroundColor','red')
set(handles.Num1, 'ForegroundColor','red')
end
I would like to use Obj to replace handles.Num1. is there any way to do this?

Akzeptierte Antwort

Adam
Adam am 1 Sep. 2017
handles.( [ 'Num', num2str( button ) ] )
should work, although quite what you are doing with Button I can't work out
for Button = 1
is pointless and
Button = num2str(Button);
overwriting the loop variable is also not good code.
  2 Kommentare
Peng Zhao
Peng Zhao am 1 Sep. 2017
Thank you, this works. And because Button was only a temp variable that I used for the loop, that's why I was overwriting it.
Adam
Adam am 1 Sep. 2017
loop variables are usually temporary, but you don't overwrite them in the loop.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by