MATLAB: Loading a certain column from an ascii file to a list box in gui matlab

edit boxguilistboxMATLAB

Hello,
I am trying to load the content of a certain column in an ascii file where the column number is given by an edit box like that:
[filename pathname] = uigetfile({'*.dat;*.txt','ASCII Files';'*.*','All Files' },'Look for MELT data','MultiSelect','on');
fullpathname=strcat(pathname , filename);
x = fileread(fullpathname);
tScan = textscan(x, '%s %f %s','headerlines',1);
newScan = tScan{:};
col=getappdata(0,'edit16');% to read the entered column in the edit box
G=newScan(:,col);
set(handles.edit18,'string',G);
The problem is: if I entered the column number (col) as 1 it gives the correct content. But if entered any other number for (col) I get the following error
Index exceeds matrix dimensions.
Error in gui3>pushbutton8_Callback (line 406)
G=newScan(:,col);
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in gui3 (line 46)
gui_mainfcn(gui_State, varargin{:});
Error in
matlab.graphics.internal.figfile.FigFile/read>@(hObject,eventdata)gui3('pushbutton8_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating UIControl Callback
Could someone help me?

Best Answer

It is a bad idea to store variables globally:
col=getappdata(0,'edit16')
If you open several instances of the GUI, they overwrite the application data of the root object. This suffers from the same horror as using global. I guess, that this is much easier and safer:
col = get(handles.edit16, 'String')
We cannot know, where the value of getappdata(0,'edit16') has been set to which value. Even for you it is not trivial to find out, where and when this value was set. But you can use at least the debugger to find the value:
dbstop if error
Now Matlab stops, when an error occurs and you can check the value of col.