omfg
omfg

Reputation: 55

Saving a literal file name as a variable in Matlab

My goal is to load some files listed in the table, extract the data, and save the results as a variable of the first file name. The lists in the table are user-input characters, which represent the names of the files that will be loaded soon. I'll give you an example because you may not understand what I mean. When A,B,C (strings) are listed in the table, my code will find where they are located(eg A.txt) and load their data. After the data has been collected from them, the results are saved in the name of the table like this : A(variable)= result_data(:4). Here is my code. please let me know the wrong place. (Note that table is nx1 cell array using uitable.)

function pushbutton1_Callback(hObject, eventdata, handles)

data = get(handles.uitable,'data'); % get strings in table
for i = 1:size(data(:,1))  % count the #strings

fid = fopen([ data(i),'.csv' ]); %load the data and extract what I need
...
fclose(fid);
data(i) = result(row_1:row_2 , 4)  % this is the result_data 
% data(i) is variable string, so I am not sure whether to use the eval function.

end

Upvotes: 0

Views: 141

Answers (1)

Aero Engy
Aero Engy

Reputation: 3608

Without having your table to debug further here is my suggestions. data is probably a cell array since you are pulling it from a uitable as below.

data = get(handles.uitable,'data'); % get strings in table

So this line should error:

fid = fopen([ data(i),'.csv' ]);

Change it to this:

fid = fopen([ data{i},'.csv' ]); 

or this:

fid = fopen([ char(data(i)),'.csv' ]); 

When saving your results to the variable name which matches your string I would suggesting using a structure with dynamic field names instead of a bare variable ... otherwise you will probably have to use eval which should be avoided.

So this (which isn't what you asked for):

data(i) = result(row_1:row_2 , 4)  % this is the result_data 

Should become:

outData.(data{i}) = result(row_1:row_2 , 4)  % this is the result_data 

If data is a cell array like you said containing {'A','B','C',...} Then outData would be of the form below and contain each results.

outData.A
outData.B
outData.C

Upvotes: 0

Related Questions