non-rectangular text file upload

1 view (last 30 days)
leo
leo on 25 Jan 2012
Hi,
I have a text file in the following form:
var1, val
var2, val
var3, val, val, val
var4, val, val
var6, val
so each line represent a variable that can be either a float or a vector of float. I would like to import this data in matlab where I would have a variable named var1 that would contain the values given in the text file, and so forth.
I have looked at various documentations but i cannot find something that work for my case: there should be a same number of column and I cannot figure out how to have that variable name in my matlab code.
Thanks for your help/suggestions! Leo

Accepted Answer

Andrew Newell
Andrew Newell on 25 Jan 2012
This will do it:
fid = fopen('data.csv');
tline = fgetl(fid);
while ischar(tline)
ind = find(tline==',',1,'first');
eval([tline(1:ind-1) '= [' tline(ind+1:end),']']);
tline = fgetl(fid);
end
fclose(fid)
If you don't want to see the output, you can replace the eval line by
S = evalc([tline(1:ind-1) '= [' tline(ind+1:end),']']);
EDIT: If you wish to follow Walter's advice and put all your variables in a structure, you could do the following:
fid = fopen('data.csv');
S = struct;
tline = fgetl(fid);
while ischar(tline)
ind = find(tline==',',1,'first');
S.(tline(1:ind-1)) = str2num(tline(ind+1:end));
tline = fgetl(fid);
end
fclose(fid);
  1 Comment
Walter Roberson
Walter Roberson on 25 Jan 2012
No eval! No eval! Use dynamic structure fields!
http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F

Sign in to comment.

More Answers (1)

leo
leo on 26 Jan 2012
Thanks for your help!
I changed it a bit as my file is slightly different, e.g.:
var1 3.2 3.3
var2 string1 string2
var3 124
so here is what i wrote:
fid = fopen('test.txt');
s = struct;
tline = fgetl(fid);
while ischar(tline)
arr = regexp(tline,'\t+','split'); % split line with delimiter tab and consecutive as one
ind = length(char(arr(1)));
if ind > 0 % check for empty lines
var_name = tline(1:ind);
val = arr(2:end);
if not (isempty(str2num(val{1}))) % check if data is numeric
val = cellfun(@str2num, val); % if numeric convert to double
s.(var_name) = val;
else
s.(var_name) = val; % for string variables keep cell array
end
end
tline = fgetl(fid);
end
fclose(fid);
what do you think? clean?

Community Treasure Hunt

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

Start Hunting!