Incompatible Array Sizes Error
Show older comments
I am attempting to write a script that allows a user to filter a list of parks by either Country, State, or City. The data is stored in an excel spreadsheet as CSV's. The script will first ask the user how they want to filter the data (Country, State, City) and, based on the user input a set of statements should execute allowing the user to input either the specific Country, State, or City and returning the parks located there. My script works if Country is initially entered. However, if State or City is entered, I get an error stating "Arrays have incompatible sizes for this operation". If I comment out the if/elseif statements for Country and City then the State input is accepted and the script works as normal. If I comment out Country and State then the City input is accepted and works as normal. However, when I leave them all uncommented, the error occurs. What am I missing?
Section 1
T=readtable('BaseballParks.csv');
columnTitle=input('Would you like to search by Country, State, or City? ','s')
columnFilter(columnTitle)
Section 2
function filtertype=columnFilter(columnTitle)
T=readtable('BaseballParks.csv');
filterselection=table2array(T(:,columnTitle));
if columnTitle=='Country'
i2=input('Please enter the abbreviation of the country to be searched: ','s');
countryChoice=ismember(filterselection,i2);
parksCountry=T(countryChoice,:)
disp(parksCountry)
elseif columnTitle=='State'
i2=input('Please enter the abbreviation of the state to be searched: ','s');
stateChoice=ismember(filterselection,i2);
parksState=T(stateChoice,:)
disp(parksState)
elseif columnTitle=='City'
i2=input('Please enter the city to be searched: ','s');
cityChoice=ismember(filterselection,i2);
parksCity=T(cityChoice,:)
disp(parksCity)
end
end
Accepted Answer
More Answers (1)
Gonzalo Martínez de Pissón
on 9 Feb 2022
I usually use switch for cases like this. Check the code below:
function filtertype=columnFilter(columnTitle)
T=readtable('BaseballParks.csv');
filterselection=table2array(T(:,columnTitle));
switch columnTitle
case 'Country'
i2=input('Please enter the abbreviation of the country to be searched: ','s');
countryChoice=ismember(filterselection,i2);
parksCountry=T(countryChoice,:)
disp(parksCountry)
case 'State'
i2=input('Please enter the abbreviation of the state to be searched: ','s');
stateChoice=ismember(filterselection,i2);
parksState=T(stateChoice,:)
disp(parksState)
case 'City'
i2=input('Please enter the city to be searched: ','s');
cityChoice=ismember(filterselection,i2);
parksCity=T(cityChoice,:)
disp(parksCity)
end
end
1 Comment
Peter Gillen
on 9 Feb 2022
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!