function with text string input and excel file

조회 수: 1 (최근 30일)
ML
ML 2022년 5월 19일
댓글: Voss 2022년 5월 19일
How can I write a function that takes input of (filename, user_input)... basically the user input would be a text string that will return the values of the corresponding string from the excel sheet.
ex: i want to get info from car model x so my input is 'x' then it returns the following:
car model color HorsePower Mileage
x red 250 20

채택된 답변

Voss
Voss 2022년 5월 19일
warning off all
get_car_info('Cars.xlsx','x')
ans = 1×4 table
carModel color HorsePower Mileage ________ _______ __________ _______ {'x'} {'red'} 250 20
get_car_info('Cars.xlsx','y')
ans = 1×4 table
carModel color HorsePower Mileage ________ ________ __________ _______ {'y'} {'blue'} 350 27
get_car_info('Cars.xlsx','z')
ans = 1×4 table
carModel color HorsePower Mileage ________ _________ __________ _______ {'z'} {'green'} 200 36
function out = get_car_info(filename,model)
T = readtable(filename);
% two ways, depending on what the input files might look like:
% 1) this finds where the user-input "model" is located in the first
% column of the table, which may or may not be called "carModel":
out = T(strcmp(T{:,1},model),:);
% 2) this finds where the user-input "model" is located in "carModel"
% column of the table, which may or may not be the first column:
out = T(strcmp(T.carModel,model),:);
end
  댓글 수: 4
ML
ML 2022년 5월 19일
Thanks thats reallly helpful. What I meant to aask is what if my input is 'z' but its not there how could I get an error for that?
Voss
Voss 2022년 5월 19일
Including an error check for unmatched specified model:
function out = get_car_info(filename,model)
if ~nargin
error('not enough input arguments'); % error if no inputs
elseif nargin < 2
model = 'x'; % default model value if only one input
end
T = readtable(filename);
% two ways, depending on what the input files might look like:
% 1) this finds where the user-input "model" is located in the first
% column of the table, which may or may not be called "carModel":
idx = strcmp(T{:,1},model);
% 2) this finds where the user-input "model" is located in "carModel"
% column of the table, which may or may not be the first column:
idx = strcmp(T.carModel,model);
% in either case, check that there is a valid model match:
if ~any(idx)
error('model %s does not appear in the table',model);
end
% return the sub-table matching model:
out = T(idx,:);
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by