importing vectors from text file
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I want to import data into matlab which is in following format
-1 1:167.000000 2:178.000000
+1 1:162.000000 2:31.000000...
where 1 to 167 is supposed to be a vector containing numbers from 1 to 167 How should i do this?
0 commentaires
Réponses (1)
dpb
le 6 Nov 2016
Modifié(e) : dpb
le 7 Nov 2016
What would you expect the result to be for each input record?
Looks like one of the few places for eval, though...read the records as text and execute the code after wrapping each in brackets as
[-1 1:167.000000 2:178.000000]
NB: Each of these is going to be a resulting vector of different length so you won't be able to place them in a conventional array but would have to use cell array to hold the result.
ADDENDUM
>> fid=fopen('muh.txt');
>> while ~feof(fid)
l=fgetl(fid);
t=tokens(l);
j=j+1;c{j,1}=str2num(t(1,:));
for i=2:size(t,1)
c{j,i}=eval([ t(i,:) ';']);
end
end
>> c
c =
[-1] [1x167 double] [1x177 double]
[ 1] [1x162 double] [1x30 double]
>> fid=fclose(fid);
tokens is a simple parser that returns character array...
>> type tokens
function tok = tokens(s,d)
% Simple string parser returns tokens in input string s
%
% T=TOKENS(S) returns the tokens in the string S delimited
% by "white space". Any leading white space characters are ignored.
%
% TOKENS(S,D) returns tokens delimited by one of the
% characters in D. Any leading delimiter characters are ignored.
% Get initial token and set up for rest
if nargin==1
[tok,r] = strtok(s);
while ~isempty(r)
[t,r] = strtok(r);
tok = strvcat(tok,t);
end
else
[tok,r] = strtok(s,d);
while ~isempty(r)
[t,r] = strtok(r,d);
tok = strvcat(tok,t);
end
end
A cleaner version w/o the use of eval would look something like-- (Caution: air code; untested)
fid=fopen('muh.txt');
x=cell2mat(textscan(fid,'%f' repmat('%f:%f',1,2)],'collectoutput',1));
fid=fclose(fid);
[R,C]=size(x);
for j=1:R
c{j,1}=x(j,1);
for i=2:2:C
c{j,i/2}=[x(j,i):x(j,i+1)];
end
end
I recommend the latter over the former about 10:1...
Voir également
Catégories
En savoir plus sur String Parsing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!