Help with assignment on functions

I cannot understand how to complete this at all:
1. The cost of sending a package by an express delivery service is $15 for the first two pounds, and $4.25 for each pound over two pounds. Write a program that computes the cost of mailing the packages. Your program must use a function to calculate the cost. Use the test data: 1.5 16 103 lbs The data should be read by the main program from a text file. The data is passed to the function. The results and any other output should be printed by the main program.
Function I have so far:
function x=cost(a)
for k=1:length(a)
if a(k)<= 2
x=15;
else a(k)>2
x=15+4.25*(a-2);
end
end
Program
clc
clear
disp(' name')
disp(' Project 8 problem 1')
ffrd1=fopen('weight.txt','rt');
a=fscanf(ffrd1,'%f',3);
fclose(ffrd1);
co=cost(a)
fprintf('%5f',co)
This is the error I'm getting:
Error in cost (line 2) for k=1:length(a)
Output argument "x" (and maybe others) not assigned during call to "/Users/jdickman/Desktop/Matlab/cost.m>cost".
Error in a10_1 (line 8) co=cost(a)

Answers (5)

function x=cost(a)
This mean you are calculating x depending on the value of a. In your code x is not calculated. You should correct this (elseif instead of else)
if a(k)<= 2
x=15;
elseif a(k)>2
x=15+4.25*(a-2);
end
%or
if a(k)<= 2
x=15;
else
x=15+4.25*(a-2);
end
Oh okay. So that helps, but now the problem is the function is not calculating the first weight (1.5) correctly. It should read be calculated as 15 (since it is less than 2lbs), but instead the function is putting it through the x=15+4.25*(a-2) part.
function x=cost(a)
for k=1:length(a)
if a(k)<= 2
x=15;
elseif a(k)>2
x=15+4.25*(a-2);
end
end
Which outputs:
12.875000
74.500000
444.250000
the 12.875 is the 1.5lb weight, but it should be 15

1 Comment

function x=cost(a)
for k=1:length(a)
if a(k)<= 2
x(k)=15;
elseif a(k)>2
x(k)=15+4.25*(a(k)-2);
end
end
Best wishes
Torsten.

Sign in to comment.

Josh Dickman
Josh Dickman on 1 Dec 2014
Awesome! Thanks for the help. Could you explain why that worked?

2 Comments

Sure.
In your version, the x variable looks like
for k=1: x=15
for k=2: x=[12.875000 74.500000 444.250000]
for k=3: x=[12.875000 74.500000 444.250000]
In my version, it looks like
for k=1: x=15
for k=2: x=[15 74.500000]
for k=3: x=[15 74.500000 444.250000]
So don't set the return vector x as a whole for each k, but elementwise.
And you should allocate the x vector as
x=zeros(length(a))
when you enter your cost function.
Best wishes
Torsten.
Ok, thanks! That was really helpful!

Sign in to comment.

function c = cost(a)
n = numel(a);
c = 15*ones(n,1);
k = a(:) - 2;
l0 = k > 0;
c(l0) = c(l0) + k(l0)*4.25;
end
Mainak Kundu
Mainak Kundu on 10 May 2020
function [cost]=package_weight(w)
if w<=2
cost=15;
else cost=15+4.25*(w-2)
end

Tags

Asked:

on 1 Dec 2014

Answered:

on 10 May 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!