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!
0 件のコメント
回答 (1 件)
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 件のコメント
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 Center および File Exchange で Entering Commands についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!