In: Computer Science
Q66. Two stores (A, B) both sell one product. The sales data for each day is shown in the following table (use variable T for the table). The first column is used to identify the stores (A and B); the 2nd column is the unite price of the product on that day; the 3rd column is the number of sold product on each day.
store price |
Price |
count |
A |
25 |
10 |
A |
26 |
9 |
B |
20 |
18 |
… |
… |
… |
B |
22 |
18 |
(1) Get a sub-table (T2) which includes only the sales data for store A (all three columns).
(2) Calculate average (unit) price, maximum price for store A.
(3) Calculate the total sale amount for store A. That is, 25*10 + 26*9 + 20*18 + ... + 22*18. Solve this without using loop and using loop.
I need help to solve this in MATLAB programming...please
Without using Forloop
% sample data
stores = ['A'; 'A';'B';'A';'B';'A';'B'];
Price = [25; 26; 20; 22; 24; 30; 40];
count = [10; 9; 18; 7; 6; 18;12];
T = table(stores, Price, count)
% slicing stores with A
T2 = T(T.stores=='A',:)
% calculating average Price of store A
avgUnitPrice = mean(T2.Price);
% calculating maximum Price of store A
maxPriceStoreA = max(T2.Price);
% calculating total sales of store A
totalSaleOfStoreA = sum(T2.Price .* T2.count);
% printing data
fprintf("Average Price of store A : %f\n", avgUnitPrice);
fprintf("Maximum price for store A : %f\n", maxPriceStoreA);
fprintf("Total Sale Amount of store A : %f\n", totalSaleOfStoreA);
Code
Output
Using For Loop
% sample data
stores = ['A'; 'A';'B';'A';'B';'A';'B'];
Price = [25; 26; 20; 22; 24; 30; 40];
count = [10; 9; 18; 7; 6; 18;12];
T = table(stores, Price, count)
% slicing stores with A
T2 = T(T.stores=='A',:)
avgUnitPrice = 0;
maxPriceStoreA = T2.Price(1);
totalSaleOfStoreA = 0;
sumOfPrices = 0;
% calculating sumOfPrices, maxPrice, totalSales
% using for loop
for row = 1:length(T2.stores)
% slicing and summing values
sumOfPrices = sumOfPrices + T2(row,:).Price;
if maxPriceStoreA < T2(row,:).Price
maxPriceStoreA = T2(row,:).Price;
end
totalSaleOfStoreA = totalSaleOfStoreA + T2(row,:).Price*T2(row,:).count;
end
% calculating average
avgUnitPrice = sumOfPrices/length(T2.stores);
% printing data
fprintf("Average Price of store A : %f\n", avgUnitPrice);
fprintf("Maximum price for store A : %f\n", maxPriceStoreA);
fprintf("Total Sale Amount of store A : %f\n", totalSaleOfStoreA);
Code
Output