Get value out of file when selecting a header.

% --- Executes on button press in LoadFile.
function LoadFile_Callback(hObject, eventdata, handles)
% hObject handle to LoadFile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on selection change in listbox1.
%get information from file
filename = 'myfile02.txt'
fid = fopen(filename)
formatSpec = '%s'
Data = textscan(fid,formatSpec,'Delimiter','\t')
%get the headers
ShowData = Data{1:1}
Header = ShowData(1:1)
Headerchar = char(Header)
TotalHeader = strsplit(Headerchar)
ReaderHeader = TotalHeader(2:end)
%set the headers into a listbox
set(handles.listbox1,'String',ReaderHeader)
% --- Executes on button press in GetFigure.
function GetFigure_Callback(hObject, eventdata, handles)
% hObject handle to GetFigure (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%get what is selected in the listbox
LBString = get(handles.listbox1,'String')
LBValue = get(handles.listbox1,'Value')
LB = LBString(LBValue)
%INFORMATION IN 'myfile02.txt'
% 'days/names Day1 Day2 Day3 Day4 Day5 Day6 Day7'
% 'Martin 95.01 76.21 61.54 40.57 5.79 20.28 1.53'
% 'John 23.11 45.65 79.19 93.55 35.29 19.87 74.68'
% 'Jeff 60.68 1.85 92.18 91.69 81.32 60.38 44.51'
% 'Frederic 48.60 82.14 73.82 41.03 0.99 27.22 93.18'
% 'Carl 89.13 44.47 17.63 89.36 13.89 19.88 46.60'
So say: LB = 'Day5'
I want know how I can get the information underneath the header 'Day5'. This is without knowing for hand what the headers are.
The outcome should be:
Headerinformation = '5.79' '35.29' '81.32' '0.99' '13.89'
If anyone could help me I would be gratefull

 Accepted Answer

If you use readtable() then you can index by field name.
Otherwise, strcmp() against the header to figure out which column number you need and use that to index Data

3 Comments

I can use strcmp(), in a for loop to get the i:i to find the row to look in to, but I find it difficult to work with readtable() to read the row. Is there another function which can look into a cell or do I need to seperate the cell into different strings and use:
Data = ShowData(2:end,i:i)?
I would recommend changing the way you read. After you fopen the file, I suggest using fgetl() to read the header line, which you can then strsplit() to get the column headers. Then textscan() with a format of ['%s' repmat('%f',1,7)] and probably with 'CollectOutput', 1 . Then you can strcmp() against the first cell returned to get the row index, and you can strcmp() against the header to get the column index, and then index the result.
It works now. Thank you very much!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!