Borrar filtros
Borrar filtros

Using fgetl for .dat data set

2 visualizaciones (últimos 30 días)
Victoria Gonzalez Canalle
Victoria Gonzalez Canalle el 23 de Mzo. de 2020
Comentada: Walter Roberson el 24 de Mzo. de 2020
Hi everyone!
I'm looking for some guidance on using fgetl and for loops to iterate through a data set and complete a computation.
The data set has three columns: part number, cost, quantity (in this order).
My goal is to iterate through the data and get total dollar amount of all inventory.
Here is my code:
% creating the file parts_inv.dat. Do not change the following lines:
qwerty = fopen('parts_inv.dat','w');
for i = 1:randi([10,20]) fprintf(qwerty,'%d %.2f %d\n',randi([100,200]),rand()*10+5,randi([20,100])); end
fclose('all');
% read the file 'parts_inv.dat' into partsmat using fgetl
fid = fopen('parts_inv.dat');
count = 0;
while true
if ~ischar(fgetl(fid)); break; end
count = count +1;
end
partsmat = fgetl(fid);
% compute the total dollar amount of the inventory:
amount = zeros(1,count);
for i = 1:count
[first, rest] = strtok(partsmat);
[cost, quant] = strtok(rest);
amount(1,i) = double(cost)*double(quant);
end
total_amount = sum(amount);
fclose('all');
The error I am currently getting is:
Unable to perform assignment because the size of the left side is
1-by-1 and the size of the right side is 0-by-0.
Error in fgetl9_1 (line 20)
amount(1,i) = double(cost)*double(quant);
Anything helps!

Respuestas (1)

Walter Roberson
Walter Roberson el 23 de Mzo. de 2020
You count the lines until end of file. Then you try to read another line. But you are ready at the end of the file so there is nothing there to parse.
If you posted a sample file we could make suggestions. Based on what you have posted before the suggestion is likely to involve using readtable or readmatrix if you have r2019b or later
  2 comentarios
Victoria Gonzalez Canalle
Victoria Gonzalez Canalle el 23 de Mzo. de 2020
This is all the information that I have, since this is an exercise for a course I am taking I do not have any more information than what I have provided. What suggestios do you have based on this code?
Walter Roberson
Walter Roberson el 24 de Mzo. de 2020
After you do the counting
frewind(fid)
And your fgetl into partsmat needs to go into the for i loop.
Your tokens are character vector. double() applied to a character vector returns the character codes, such as double('15') will return 49 53 because 49 is the character code that corresponds to '1'. You need to figure out how to convert from character vectors to the numbers that they represent.

Iniciar sesión para comentar.

Categorías

Más información sobre Entering Commands en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by