14.1k views
2 votes
Matlab Question:

Important! Read: No for or while loops may be used; must use the disp function
The top speeds of sportscars, given in miles per hour, are:
155 mph BMW M5
217 mph Lamborghini Aventador Spyder
205 mph Ferrari 488
205 mph Nissan GTR
197 mph Chevrolet Corvette Stingray ZR1
258 mph Bugatti Veyron Supersport
195 mph Dodge Viper
270 mph Hennessey Venom
155 mph BMW M3
195 mph Mercedes SL
Write a function selectCars to identify cars with top speed within a given range and display the identified names. The selected cars speed will be in a range given by lowerBound < speed < upperBound. Inputs to the function selectCars are a column array topSpeeds that lists of top speeds, the corresponding column array carNames with car names, and lowerBound and upperBound both given in km/h.
Given:
To display the selected carNames, for example the first two, use something analogous to disp(carNames(1:2,:))
1 mile = 1.609 kilometers
Test data sets for topSpeeds and carNames (provided in example function call)
Restriction: For and while loops may not be used.
The function call is:
function identifiedCars=selectCars( topSpeeds, carNames, lowerBound, upperBound)
For example:
selectCars( topSpeeds, carNames, 287,338)
produces:
Ferrari 488
Nissan GTR
Chevrolet Corvette Stingray ZR1
Dodge Viper
Mercedes SL

User Gil LB
by
5.2k points

1 Answer

2 votes

Final answer:

The function selectCars identifies and displays cars within a given speed range in Matlab, converting mph to km/h and using logical indexing to identify cars that meet the criteria, then displaying their names without loops.

Step-by-step explanation:

To create the function selectCars in Matlab that identifies cars with top speeds within a specified range without using for or while loops, you can utilize logical indexing. First, you need to convert the speed from miles per hour to kilometers per hour by multiplying the topSpeeds array by 1.609. Finally, use the disp function to display the car names that meet the criteria. Here's a step-by-step example of how the function should be written:

Function Definition

function identifiedCars = selectCars(topSpeeds, carNames, lowerBound, upperBound)
% Convert mph to km/h
topSpeedsKmh = topSpeeds * 1.609;
% Find cars within the speed range
withinRange = topSpeedsKmh > lowerBound & topSpeedsKmh < upperBound;
% Select the car names that meet the speed criteria
identifiedCars = carNames(withinRange, :);
% Display the car names
disp(identifiedCars);
end

When you call selectCars(topSpeeds, carNames, 287, 338), it will display the car names whose top speeds are greater than 287 km/h and less than 338 km/h, as seen in the given example.

User Perotom
by
5.5k points