필터 지우기
필터 지우기

Using fgetl for .dat data set

조회 수: 2 (최근 30일)
Victoria Gonzalez Canalle
Victoria Gonzalez Canalle 2020년 3월 23일
댓글: Walter Roberson 2020년 3월 24일
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
Victoria Gonzalez Canalle 2020년 3월 23일
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