MATLAB: CSV convert will not work with string file name

csvwriteguihandles

Hello,
I am writing a GUI to convert parts of .mat files into excel files.
the variables tht are to be converted are stored in a listbox entitled 'listbox2' To clarify where they came from I am trying to put the name of the .mat file on them as a prefix but I cannot seem to get the output files to show up at all.
Worse, this fails to generate any errors. I run the csvwrite command but nothing happens.
Here is the code:
function convert_button_Callback(hObject, eventdata, handles) % hObject handle to convert_button (see GCBO) % eventdata reserved – to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)
filelocation = get(handles.MAT_file, 'string');
loadfile =['load ''' filelocation ''''];
eval(loadfile);
%evaluate the sting as if it were a command. See notes on %apostrophies for this one. %eval(['varlist = who(''-file'' , ''' filelocation ''');']);
exportlist = get(handles.listbox2,'string')
%we need to change the directory to the chosen output and after we have %re-loaded the .mat file into the workspace convert the files %The evalin evaluates the expression in 'base' or workspace
for a = 1:length(exportlist) finaltag = strcat(filelocation, exportlist{a})
outloc = get(handles.CSV_file, 'string');
cdstring = ['cd(''' outloc ''')'];
eval(cdstring);
csvwrite([finaltag,'.csv'],evalin('base',exportlist{a}))
%Orional code
%csvwrite([exportlist{a},'.csv'],evalin('base',exportlist{a}))
end

Best Answer

Your code can be considerably simplified. Yes, I know the below code is much longer, but I added a lot of error checking; the heart of the code is small and efficient.
olddir = cd;
outloc = get(handles.CSV_file, 'string');
try
cd(outloc);
catch
error(sprintf('failed to cd to %s', outloc));
end
filelocation= get(handles.MAT_file, 'string');
try
S = load(filelocation);
catch
error(sprintf('failed to load file %s', filelocation));
end
for a = 1:length(exportlist)
v = exportlist{a};
if isfield(S, v)
finaltag = [filelocation, v, '.csv'];
try
csvwrite([finaltag,'.csv'],S.(v));
catch
warning(sprintf('was unable to write variable %s to file %s', v, finaltag));
end
else
warning(sprintf('input file %s does not contain variable %s, csv not written for variable', filelocation, v))
end
end
cd(olddir)