how to import data

5 views (last 30 days)
Andy
Andy on 21 Jul 2012
So after reading how to import data from a text file, my .m file is still not compiling.
I am trying to import a text file that has two columns into my file. In the documentation, textscan(filename) is the correct solution but what is in the filename? Is is the path of where the file is located on the computer?

Answers (2)

Image Analyst
Image Analyst on 21 Jul 2012
Edited: Walter Roberson on 22 Jul 2012
No. First of all, textscan() take a file handle or a character string with data in it, not a string filename.
Next, be ware that the folder where your exe lives is not your default folder. Surprise surprise! Of course you were using risky and dangerous non-robust code to assume that your data file would be in the default folder in the first place. You should not even do that with an m-file you are running in the MATLAB develoment environment. You must use fullfile() and exist() (unless you use uigetfile()) to build your path at some known location. See the FAQ: http://matlab.wikia.com/wiki/FAQ#Where_did_my_file_go.3F_The_risks_of_using_the_cd_function.
If you really want to find out where the "real" current folder is, then put this line in your startup code:
fprintf('Current folder = %s\n', pwd);
fprintf('ctfroot = %s\n', ctfroot);
I think you'll find that your current folder is equal to your ctfroot (or nearby) which is not where your exe is, unless you changed it with the cd function in the startup.m file. Your startup.m file gets compiled and built into your executable and it will get run, so if you want a certain known folder to be the current folder, put this line in your startup.m file:
if isdeployed
cd('c:\my current folder'); % or wherever you want it to be.
end
Or you could do that in the startup code section of your app. But again, you must build up your filename. First specify the folder, and then specify the basefilename+extension. Then use fullfile() to combine them. Then use exist(fullFileName, 'file') to check that it really exists before you try to pass it to any function.

per isakson
per isakson on 21 Jul 2012
Doc says:
Import Numeric Data from a Text File
You can import any ASCII data file with numeric fields easily
by selecting File > Import Data or by calling importdata.
Try:
A = importdata( 'c:\my_data\etc\my_data_file.txt' );

Categories

Find more on Data Import and Analysis in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!