Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MATLAB- A file \"parts_inv.dat\" contains on each line a part number, cost, and

ID: 3806706 • Letter: M

Question

MATLAB- A file "parts_inv.dat" contains on each line a part number, cost, and quantity in inventory, in the following format:

123 5.99 52

Use fscanf to read this information into the matrix "partsmat" and store the total dollar amount of the inventory (the sum of the cost multiplied by the quantity for each part) in the variable "total_amount". You do not need to error-check the file open or close.

This is what I have so far:

% creating the file parts_inv.dat.

qwerty = fopen('parts_inv.dat','w'); for i = 1:randi([10,20]) fprintf(qwerty,'%d %.2f %d ',randi([100,200]),rand()*10+5,randi([20,100])); end

fclose('all');

% read the file 'parts_inv.dat' into partsmat using fscanf

qwerty=fopen('parts_inv.dat','w');

partsmat = fscanf(qwerty,'%3.1f',[1,3])

fclose('all');

% compute the total dollar amount of the inventory:

total_amount = partsmat

Explanation / Answer

fileID = -1; %Error handling.
errmsg = '';
while fileID < 0
disp(errmsg);
filename = input('Open file: ', 's'); %input the file name
[fileID,errmsg] = fopen(filename); %throw error if file doesnt exixts and loops till user enter valid filename
end
%part number, cost, and quantity
formatSpec = '%d %f %d';
sizeA = [3 Inf];
A = fscanf(fileID,formatSpec,sizeA);
partsmat=A' %store in partsmat marix
sum=0; %to calculate total sum
fclose(fileID);
rows=size(partsmat);
row=rows(1); %get the number of rows in file
for i=1:row %loop to gt that many rows
%disp (partsmat(row+i))
%disp(partsmat((2*row)+i))
sum=sum+partsmat(row+i)*partsmat((2*row)+i); % sum of the cost multiplied by the quantity for each part
end
total_amount=sum %displat total_amount