MATLAB: How to create a function that takes distance as vector and return distance and time travel by light

for loopmatrix manipulationvector

Hi every one. I am going to create a function which has following specification. Write a function called light_time that takes as input a row vector of distances in miles and returns two row vectors of the same length. Each element of the first output argument is the time in minutes that light would take to travel the distance specified by the corresponding element of the input vector. To check your math, it takes a little more than 8 minutes for sunlight to reach Earth which is 92.9 million miles away. The second output contains the input distances converted to kilometers. Assume that the speed of light is 300,000 km/s and that one mile equals 1.609 km. I am using that code
function [time,distance]=light_time(dis)
for i=1:length(dis)
time(i)=1/92.9*dis(i)
distance(i)=1.609*dis(i)
end
end
but getting time and distance every time the for loop run.I want to gets two vectors in final output which show the time and distance travel by the light.Guide me where i set my code to get two final vectors.
Thanks in advance.......

Best Answer

Very close (it's great that you at least tried, unlike most students), but you should put the distance calculation before the time calculation. And time() is a built in function so you don't want to use that as a variable name. Just switch those lines and give the variables a little more descriptive names
function [timeInMinutes, distanceInKm]=light_time(distanceInMiles)
distanceInKm = 1.609 * distanceInMiles;
timeInSeconds = distanceInKm / 300000
end
No for loop needed. I trust you know how to finish it and get the time in minutes. To check/test, pass in 92.9 million miles:
timeInMinutes, distanceInKm] = light_time(92900000)
Related Question