Incompatible Array Sizes Error
이전 댓글 표시
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
채택된 답변
추가 답변 (1개)
Gonzalo Martínez de Pissón
2022년 2월 9일
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
카테고리
도움말 센터 및 File Exchange에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!