Help with assignment on functions
Show older comments
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)
Azzi Abdelmalek
on 1 Dec 2014
Edited: Azzi Abdelmalek
on 1 Dec 2014
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
Josh Dickman
on 1 Dec 2014
1 Comment
Torsten
on 1 Dec 2014
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.
Josh Dickman
on 1 Dec 2014
0 votes
2 Comments
Torsten
on 1 Dec 2014
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.
Josh Dickman
on 1 Dec 2014
Andrei Bobrov
on 1 Dec 2014
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
on 10 May 2020
0 votes
function [cost]=package_weight(w)
if w<=2
cost=15;
else cost=15+4.25*(w-2)
end
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!