printing multiple variables outside of a function

This is the prompt i am given:
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.
The issue i have is printing outside of the function, and in the main program. Heres what i have so far:
Main program:
clc
clear
disp(' name')
disp(' Project 8 problem 1')
ffrd1=fopen('data81.txt','rt');
wei=fscanf(ffrd1,'%f',3);
fclose(ffrd1);
co=cost(wei);
fprintf('%5f',co);
Function:
function [x,y,z]=cost(a)
if a<= 2
x=15;
elseif a<= 100
y=15+4.25*(a-2);
else
z=5; (this was just a test number until i got it working)
end
Any help would be greatly appreciated.

3 comentarios

I think i might be on the right track?
function [x,y,z]=cost(a)
for k=1:length(a)
if a(k)<= 2
x=15;
elseif a(k)<= 100
y=15+4.25*(a-2);
else
z=5;
end
end
Jan
Jan el 4 de Mayo de 2014
Please format your code properly. Use the "{} Code" button.
Do not forget to explain, which problems the shown code has. The less the readers have to guess, the more likely is a useful answer.
ok i think i may have gotten it. i just need to take care of the anesthetics of it. Thank you very much.

Iniciar sesión para comentar.

 Respuesta aceptada

Jan
Jan el 4 de Mayo de 2014
Editada: Jan el 4 de Mayo de 2014

0 votos

You are almost ready. The only problem I see is, that the function cost() should not return 3 outputs, but a vectzor of the same size as the input. Then the simple if branches cannot work, because if needs a scalar argument. So either insert a for loop over all elements of the input, or use a so called vectorized method. I recommend to start with the loop at first.
The output should be printed with a separator, so append a '\n' to the format string of fprintf.

Más respuestas (0)

Categorías

Más información sobre File Operations en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 4 de Mayo de 2014

Comentada:

el 4 de Mayo de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by