MATLAB Answers

0

function variable undefined. How to declare it ? Says Totalcost not defined

Asked by kun wang on 23 Apr 2019 at 17:45
Latest activity Commented on by kun wang on 23 Apr 2019 at 18:12
clc
clear
A=input('please enter the items description: ');
B=input('please enter the unit cost for each item: ');
C=input('please enter the number of each item: ');
cost1=B(1)*C(1);
cost2=B(2)*C(2);
cost3=B(3)*C(3);
cost4=B(4)*C(4);
cost5=B(5)*C(5);
for i = 1:length(A)
Totalcost=cost1+cost2+cost3+cost4+cost5;
end
fprintf('Item ID: Unit Cost: Quantity: Total Cost:\n%s %5.2f %d %5.2f',A(1),B(1),C(1),cost1)
fprintf('\n%s %5.2f %d %5.2f',A(2),B(2),C(2),cost2)
fprintf('\n%s %5.2f %d %5.2f',A(3),B(3),C(3),cost3)
fprintf('\n%s %5.2f %d %5.2f',A(4),B(4),C(4),cost4)
fprintf('\n%s %5.2f %d %5.2f',A(5),B(5),C(5),cost5)
function[]=Budgetcompare(s)
if Totalcost < s
fprintf('the total cost of %4.2f is less than your budget!', Totalcost)
elseif Totalcost == s
fprintf('the total cost of %4.2f is exactly your budget!', Totalcost)
else
fprintf('the total cost of %4.2f is more your budget!', Totalcost)
end
end

  0 Comments

Sign in to comment.

1 Answer

Answer by Guillaume
on 23 Apr 2019 at 17:58

What you have written is a script (name unknown) with a local function called Budgetcompare. A function (local or normal) never has access to variables defined outside of it. You need to pass the required variables as arguments.
Also, a function needs to be called for it to run.
It looks like you would benefit to learn about function basics. Your function may look like:
function[]=Budgetcompare(s)
if Totalcost < s
fprintf('the total cost of %4.2f is less than your budget!', Totalcost)
elseif Totalcost == s
fprintf('the total cost of %4.2f is exactly your budget!', Totalcost)
else
fprintf('the total cost of %4.2f is more your budget!', Totalcost)
end
end
And of course, somewhere in your code, you would call it with, for example:
Budgetcompare(totalcost, budget); %assuming that you have a variable called budget in your script.
While we're at it, you should never create numbered variables. Use indexing instead, so:
cost(1) = B(1) * C(1);
cost(2) = B(2) * C(2);
... etc
which can be simplified to just:
cost = B .* C; %calculate all of the cost at once
There are more things that are wrong with your code (pointless i loop, part of the code assume varying number of items entered, other parts fixed to 5, etc.). You need to think a bit more about what you write.

  1 Comment

Sign in to comment.