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
KSSV 2022-4-1
Are you sure they are strings? Why they are strings? Happily you can have them as numbers right?

请先登录,再进行评论。

回答(1 个)

KSSV
KSSV 2022-4-1
data_rate = '288'; % user input
permissible_rates = {'128';'256';'512'}; % validate input against this
idx = contains(permissible_rates,data_rate)
idx = 3×1 logical array
0 0 0
  5 个评论
rkoz575
rkoz575 2022-4-4
Thank you Steven for the comprehensive answer. I should have realised that contains would fail in the case you mention (where 288 is somewhere in the text). "matches" is a better function to use!
If you submit this as an answer I will accept it.
ajay kumar
ajay kumar 2022-7-6
data_rate = '288';
someRates = {'2889','1288', '72883', '288'};
find(matches(someRates,data_rate))
ans = 4
It will give right index with idx

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by