Loading matrix with text and numbers from txt file

1 visualizzazione (ultimi 30 giorni)
Ger Kais
Ger Kais il 16 Gen 2016
Commentato: Star Strider il 16 Gen 2016
I have a text file, formatted this way
ANTONIO 20 3
MARIO 100 60
and I have to read the contents of this file in a matrix, and extract the vectors with the names and the numbers in column. There are no headers and there are some simple calculation requested. I can't use textscan since cell arrays where not a subject of my university lectures. Could you help me finding some alternative ways? I can use fscanf commands but only when arrays are numeric. Sorry for my english, I'm not a native speaker.

Risposte (1)

Star Strider
Star Strider il 16 Gen 2016
Are you not allowed to use cell arrays and textscan, or do you simply need help in learning how to use them?
The textscan function is definitely the way to go here:
fidi = fopen('YourFile.txt','r');
Data = textscan(fidi, '%s%f%f');
fclose(fidi);
Here ‘Data’ will have three cell vectors, one for the name, and one for each of the other columns.
Your English is fine. You need not apologise.
  2 Commenti
Ger Kais
Ger Kais il 16 Gen 2016
Thank you for the fast answer. Well, i don't know how to handle cell vectors or arrays, and I'm not sure I can use them in the exam, it was a messy class. Can I convert these cell vectors into normal vectors? If this is the best way to solve the problem I'll adopt it.
if true
function [M] = CaricaMatMista(filename)
fid=fopen(filename,'r');
M=textscan(fid,'%s %d %d');
fclose(fid);
end
end
This is my function, and these the outputs
if true
M =
{6x1 cell} [6x1 int32] [6x1 int32]
end
What now?
Star Strider
Star Strider il 16 Gen 2016
You would address the cells similarly to the way you would address a vector, but using curly braces ‘{}’.
To get the values for the fourth person:
M = {{'qwerty'; 'uiop'; 'asdfg'; 'hjklz'}, {2 4 8 3}', {55 47 23 91}'};
Name_4 = M{1}(4)
Var1_4 = M{2}(4)
Var2_4 = M{3}(4)
Name_4 =
'hjklz'
Var1_4 =
[3.0000e+000]
Var2_4 =
[91.0000e+000]
If you post your text file (or a represetnative part of it), and want to use fscanf instead,that will help. I make it a practise not to write code for files I don’t have (other than those that can use textscan and then only if those files are well-described), because there are too many problems guessing at what the correct code is.

Accedi per commentare.

Categorie

Scopri di più su Text Data Preparation in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by