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)

回答(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 个评论

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
Josh Dickman 2014-12-1
Awesome! Thanks for the help. Could you explain why that worked?

2 个评论

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!

请先登录,再进行评论。

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 2020-5-10
function [cost]=package_weight(w)
if w<=2
cost=15;
else cost=15+4.25*(w-2)
end

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by