How to make a dynamic array in GUI?

Hi fellows,
I am trying to make dynamic arrays in GUI, where the user can keep adding new elements. It is like the user does not know the exact number of total elements at the beginning. So the user would just add new element to it until he/she is satisfied.
For example, I am going to add some new items to an array with their names. Here is what I suppose, under a pop-up menu callback:
str = get(hObject, 'String');
val = get(hObject,'Value');
handles.itemnames = {};
switch str{val};
case 'A'
???????
case 'B'
???????
case 'C'
???????
end
guidata(hObject,handles)
So my problem is: what I should write for "???????" to achieve that if the user choose 'A' from the pop-up menu and click a 'done' button, the name 'A1' will be stored in the first position of handles.itemnames array. Then if the user choose 'B', the name 'B1' will be stored in that same array at the second position. And then if the user choose another 'A', the name 'A2' will be stored in that array at the third position. The process can go on and on until the user is satisfied. The names are generated automatically with unique index number, from A1/B1/C1 to An/Bn/Cn.
Any answer or advice would be much appreciated.
Regards,
Lin

4 件のコメント

Geoff Hayes
Geoff Hayes 2016 年 6 月 19 日
Lin - to be clear, if the user selects A (from the popup menu) then the itemnames is set to {'A1'}. If the user chooses A again, then the itemnames is set to {'A1','A2'}. Is this correct? So there could be any number of AX, BY, and CZ strings?
Stephen23
Stephen23 2016 年 6 月 19 日
編集済み: Stephen23 2016 年 6 月 19 日
@Lin LIU: your code will be faster and more robust if you avoid creating and accessing variable names like that. Numbered variables often indicate that a beginner wants to try to access those variables dynamically. Much better is to simply use indexing (note that the numbers are basically an index, therefore you can make them a proper index and have much more robust code). Read this to know why:
Lin LIU
Lin LIU 2016 年 6 月 20 日
Geoff: Thank you for your attention and yes, the itemnames will go like {'A1','A2','B1','C1'...} as the user keeps adding new elements. I think there would be no limit to the number of strings. Stephen's advice is revealing. I will try if I can alter my code and make my problem clearer. Thank you!
Lin LIU
Lin LIU 2016 年 6 月 20 日
Stephen: Thank you for your valuable advice! I have been thinking about it and my original code is indeed bad. I will try to improve my code referring to your link. Thank you very much!

サインインしてコメントする。

回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeVariables についてさらに検索

質問済み:

2016 年 6 月 19 日

コメント済み:

2016 年 6 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by