Using fgetl for .dat data set

2 次查看(过去 30 天)
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!

回答(1 个)

Walter Roberson
Walter Roberson 2020-3-23
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 个评论
Victoria Gonzalez Canalle
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 2020-3-24
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by