Compare information from table to string

5 views (last 30 days)
I currently work on a project where I need to compare the input information to the information in the table and then output the row which is matching the input information. The input information is departure and arrival airport, which is represented with 3 capital letters (i.e. 'DEN', 'JFK). The flight data is stored in .txt file, which is then converted to the table in matlab. When I try to run the for loop, MATLAB outputs an error, saying that '==' cannot be used with the table. Can you please help me to solve this issue? I will attach the code and the .txt file below.
function rv = finalproject(Departure, Arrival)
routes = readtable('routes.txt'); % import routes data
planes = readtable('planes.txt'); % import planes data
airlines = readtable('airlines.txt'); % import airlines data
if length(Departure) ~= 3 % check if airport name is correct
error('Check the departure airport')
end
if length(Arrival) ~= 3 % check if airport name is correct
error('Check the arrival airport')
end
for i = 1:67663 % stop when gone through all possible
if routes(i, 3) == Departure && routes(i, 5) == Arrival % find the matching row
rv = routes(i, :); % return the matched row
end
end
end
  1 Comment
Mark Sherstan
Mark Sherstan on 19 Nov 2018
You didnt post all the .txt files so I cant confirm for sure but use strcmp() to compare the strings. You may find using the find() function to be helpful for this problem.

Sign in to comment.

Accepted Answer

Peter Perkins
Peter Perkins on 20 Nov 2018
You are correct that == doesn't work the way you have written it. You have to keep in mind that a table is a container, and so routes(i,3) is a 1x1 table while Departure is (I guess?) a 1x3 char row. Those obviously are not equal. You'd need to compare routes{i,3} to Departure, but you'd also have to use strcmp, not ==.
Allow me to suggest a few things.
1) you may want to convert your tables to timetables, since you have timestamped data.
2) I'm gonna suggest that you convert those arrival/departure data to categorical variables in your table. Among other things, that would allow you to use ==, making your code easier to read.
3) Put meaningful variable names in your table if they are not there already. This lets you say "Departure" instead of "3".
4) Most importantly, get rid of that loop.
Putting all that together, you have
j = (routes.Departure == Departure) && (routes.Arrival == Arrival);
rv = routes(j)
No loop.
Actually, your original code is kind of funny, and seems to assume only one row in your data that match the specified arrival/departure. The above will return all matches, if there are more than one.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!