How to load a file

11 vues (au cours des 30 derniers jours)
Hervé Chubaka Bagalwa
Hervé Chubaka Bagalwa le 21 Oct 2011
Hi,
To load a file, I always do this: load file.txt
But this time, my file looks like what I have pasted below.
‘load’ does not work.
How can I load a file so I can put the data into an array?
Thank you for your help.
Herve
/********************************/
The file
(6.278305337995641,-31.165930909567250)
(1.758723282034028,-1.229391225298848)
(1.133464180020400,-3.392317005428029E-001)
(3.528019029863541,9.833493189283731E-001)
(-1.589297342018588,-6.805368090065715E-001)
(-5.740909803957738E-002,5.972384666809710E-001)
(2.903057010297026E-001,-1.201455315950079E-001)
(8.626581493421666E-001,-6.836608234777217E-002)
(-1.805284473824767E-001,-5.614038990230759E-001)
(2.126569179381342,-2.150085377308474)

Réponse acceptée

Laura Proctor
Laura Proctor le 21 Oct 2011
The following code snippet will load your data into the matrix data:
fid = fopen('TestFile.txt');
M = textscan(fid,'(%f,%f)');
data = [ M{:,1} M{:,2} ];
fclose(fid);
  5 commentaires
Image Analyst
Image Analyst le 22 Oct 2011
Make sure your file is in the same directory as your m-file, or else prepend the full folder name to your base file name. Here's an example:
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'cameraman.tif';
fullFileName = fullfile(folder, baseFileName);
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
% Didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
Image Analyst
Image Analyst le 22 Oct 2011
Sorry, but comments don't allow for code formatting so it looks kind of messed up. - no indentations, etc.

Connectez-vous pour commenter.

Plus de réponses (1)

Kelly Kearney
Kelly Kearney le 21 Oct 2011
Textscan is probably your best bet here, assuming you want an n x 2 array of the paired data points. Try:
fid = fopen('file.txt');
data = textscan(fid, '(%f,%f)', 'collectoutput', true);
fclose(fid);
data = data{1};
  3 commentaires
Hervé Chubaka Bagalwa
Hervé Chubaka Bagalwa le 21 Oct 2011
Thank you for your answer
I did exactly what you did but, i got this error:
Invalid file identifier.
Hervé Chubaka Bagalwa
Hervé Chubaka Bagalwa le 22 Oct 2011
Some of the files look like this:
(-5.740909803957738E-002,5.972384666809710E-001)
I think that is the reason why i am getting errors.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Text Data Preparation dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by