MATLAB: I dont understand why this function is not working.

matlab functionsorttable

The file cars.mat contains a table named cars with variables Model, MPG, Horsepower, Weight, and Acceleration for several classic cars.
Load the MAT-file. Given an integer N, calculate the output variable mpg.
Output mpg should contain the MPG of the top N lightest cars (by Weight) in a column vector.
please help mw with the code. this is not producing correct answer.
function mpg = sort_cars(N)
load('cars.mat')
S=table(cars)
cars=sortrows(S,'Weight','ascending')
mpg =cars(1:N,'MPG');
end

Best Answer

S=table(cars)
That will not create any variable in table S that is named "Weight'.
If cars is already a table, then the result of that is that S would be a table with a single variable named cars and that single variable would be a table.
If cars is a numeric array, then you would want to use array2table() and you would want to pass in a 'VariableNames' option listing the variable names.
Related Question