Read characters from a txt file

Hello everyone. I have a txt file in which the word 'HELLO' is written. I want Matlab to read this from the text and give me a matrix of the ASCII numbers of the letters. I found and executed the following code from a video.
fid = fopen('input1.txt');
matrix = fscanf(fid,'%f %c', [1,inf])
In the 2015 Matlab version, it gives me a matrix with 9 columns. In 2020 trial version I am using it gives the following error:
"Invalid file identifier. Use fopen to generate a valid file identifier." even though I used fopen.
Any help is appreciated.

5 commentaires

dpb
dpb le 16 Mai 2020
The working directory isn't the same between the two installations -- the input file isn't being found in R2020x.
Just because you call fopen doesn't mean it is always successful...check the return code and error message it returns--
Nazli Demir
Nazli Demir le 17 Mai 2020
Thank you, I will check those. I still don't understand why the five letter word yields a result of 9 columns though.
'Pends on just what is in the file and the encoding used...for one thing also, your format string includes a '%f' for a floating point value which doesn't match the file content you described.
NB: '%c' returns any single character, including white space.
Probably what you really want is
matrix = fscanf(fid,'%s',1);
to return the word as char() string (which internally is an array of characters)
Again presuming the text is all that is in the file...
Nazli Demir
Nazli Demir le 17 Mai 2020
Writing '%s' did reduce it the number of outputs to five as I wanted. They're still not the ASCII character of the letters, but maybe I need to do something else for that. Thank you..
dpb
dpb le 17 Mai 2020
Modifié(e) : dpb le 17 Mai 2020
double()
after you read the input data.(*)
If you're going to use formatted read, the i/o formatting libraries return the type of the variable expected in the format string--and a text value in a text file is interpreted as character data. The floating point (or decimal, too, for that matter) format string won't recognize anything other than a valid number as a number; that's its purpose and sole mission in life.
You can cheat and read the file as straight binary bytes by using fread, but that is also system-dependent in what created the file as far as encoding may be for unicode, etc., ...
(*) The other idiom you may see is
v=s+0;
where s is the char() string and v the numeric values...MATLAB will silently do the conversion with the arithmetic operation of char() to double().

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Modifié(e) :

dpb
le 17 Mai 2020

Community Treasure Hunt

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

Start Hunting!

Translated by