Compare a string against list of other strings
조회 수: 21 (최근 30일)
이전 댓글 표시
Hello,
I would like to understand how to compare a user-inputted string against a list of other strings. I have some extremely verbose code that does work but I am convinced there must be a more elegant solution.
I paste example code below. I am trying to compare a "data rate" against some "permissible rates". Can anyone advise? Thank you.
clear; clc;
data_rate = '288'; % user input
permissible_rates = {'128';'256';'512'}; % validate input against this
check_rate = NaN(size(permissible_rates)); % set up empty array
% Go through the permissible rates, and see if the data rate string is the
% same of any of the permissible rates. If yes, output is 1. If no, output
% is 0
for i=1:length(permissible_rates)
check_rate(i)=strcmp(data_rate,permissible_rates{i});
end
% if there are no 1s in the array, the user input is invalid
if ismember(1,check_rate) ~= 1
error('You didn''t choose a correct data rate');
end
% otherwise continue
disp('You choose a correct data rate, congratulations')
댓글 수: 1
KSSV
2022년 4월 1일
Are you sure they are strings? Why they are strings? Happily you can have them as numbers right?
답변 (1개)
KSSV
2022년 4월 1일
data_rate = '288'; % user input
permissible_rates = {'128';'256';'512'}; % validate input against this
idx = contains(permissible_rates,data_rate)
댓글 수: 5
ajay kumar
2022년 7월 6일
data_rate = '288';
someRates = {'2889','1288', '72883', '288'};
find(matches(someRates,data_rate))
It will give right index with idx
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!