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

In MATLAB Write a function that takes a recipe and a coefficient and return a st

ID: 2084185 • Letter: I

Question

In MATLAB

Write a function that takes a recipe and a coefficient and return a string describing the adjusted recipe. The input recipe is given as a structure array where each entry describes one type of ingredient; the quantity field contains a numerical amount, whereas the unit and name fields contain strings. The output should be a string describing the recipe. See the example below. The ingredients should be separated by a comma and space and should end with a period. If an amount is not an integer, show it using 2 decimal places.

Sample

Explanation / Answer

Copy the following code to a new function file in MATLAB. Name the file multiplyrecipe_struct.m

function multiplyrecipe_struct(input,k)

% converting the struct fields into cells
quantity = {input.quantity};
unit = {input.unit};
name = {input.name};
N = length(quantity);
quantity2 = zeros(N);

for i=1:N
quantity2(i) = quantity{i}*k;
quantity2 = quantity2(:,1,:); % obtaining the scaled quantity
end

for i=1:N
if (i==N) % checking if the current entry is the last entry
if (mod(quantity2(i),1)==0) % checking if scaled quantity is an integer
fprintf('%d %s %s. ',quantity2(i),unit{i},name{i});
else
fprintf('%.2f %s %s. ',quantity2(i),unit{i},name{i});
end
else
if (mod(quantity2(i),1)==0)
fprintf('%d %s %s, ',quantity2(i),unit{i},name{i});
else
fprintf('%.2f %s %s, ',quantity2(i),unit{i},name{i});
end
end
end

end

Use the following code to test the above function. Copy the code to a new script file in MATLAB.

close all; clear all; clc;
multiplyrecipe_struct(struct('quantity',{4,1,3}, 'unit',{'','cups','tsp'}, 'name',{'eggs','milk','flour'}) ,0.5);
fprintf(' ');
multiplyrecipe_struct(struct('quantity',{0.5 4 3 3 3}, 'unit',{'lb' 'tbsp' 'tsp' 'tsp' 'cups'}, 'name',{'macaroni' 'butter' 'flour' 'mastard powder' 'milk'}),0.5);
fprintf(' ');
multiplyrecipe_struct(struct('quantity',{0.5 4 3 3 3}, 'unit',{'lb' 'tbsp' 'tsp' 'tsp' 'cups'}, 'name',{'macaroni' 'butter' 'flour' 'mastard powder' 'milk'}),2);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote