how to import numbers from a file

4 visualizaciones (últimos 30 días)
Tarek Eid
Tarek Eid el 27 de Feb. de 2020
Respondida: Divya Gaddipati el 2 de Mzo. de 2020
Hi all
i gave this text document named inventory.txt and it contais this data
part# cost quantity
127 23.44 146
643 18.20 87
443 143.19 13
801 15.34 66
I want to multiply the cost for each part by the quanatity and then add all costs to get total costs.I want to do this by extracting the costs and quantities and multiplying them. I tried using fget1(s), feof but i cant get them to work. any idea on how the extract the cost numbers and quanatity numbers?
  2 comentarios
Geoff Hayes
Geoff Hayes el 27 de Feb. de 2020
Tarek - try using importdata. Note how, if you use this function, you can ignore the header row. Out of curiosity, does your data look exactly like that with spaces between each row?
darova
darova el 27 de Feb. de 2020
Try importdata

Iniciar sesión para comentar.

Respuestas (1)

Divya Gaddipati
Divya Gaddipati el 2 de Mzo. de 2020
You can use importdata for this purpose.
d = importdata('inventory.txt');
This outputs a struct with 3 fields - "data", "textdata" and "colheaders"
data contains the numerical data in a matrix
textdata contains the text in an array of cells
colheaders contains the column headers
cost = d.data(:, 2);
quantity = d.data(:,3);
total_cost = cost .* quantity;
Hope this helps!

Community Treasure Hunt

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

Start Hunting!

Translated by