Matlab_03a

More on variables

Like all programming languages Matlab allows us to give values and results of calculations a name so we can refer to them by that name later:

cost_per_litre = 1.1;

miles_per_litre = 5;

distance_to_destination = 240;

cost_to_ destination = distance_to_ destination/miles_per_litre * cost_per_litre


cost_to_ destination =

52.8000

This is extremely useful because the last line, the one that calculates the cost_to_destination, contains no values and can be used for any journey. This takes us a step closer to writing something that we might wish to store away and use many times.

Named values are usually called `variables' by programmers because they can take any value, and the value can be changed at any time. For example having just calculated the journey cost to London from Plymouth (240 miles) we can now calculate the cost to Bristol (100 miles):

distance_to_destination = 100;

cost_to_destination = distance_to_destination / miles_per_litre * cost_per_litre


cost_to_destination = 22

We can even calculate both answers, or any number of answers, at the same time:

distance_to_destination = [240 100 300 900];

cost_to_destination = distance_to_destination / miles_per_litre * cost_per_litre


cost_to_destination =

52.8000 22.0000 66.0000 198.0000