比较两个表中的字符串matlab
comparing strings in two tables matlab
我知道 matlab 可以方便地从 table 中获取在 'a' 列中具有字符串(在本例中)desired_a 的所有行,如下所示:
refs_found = refs(strcmp(refs.a,desired_a),:);
但是,如果 desired_a 不是字符串,而是带有字符串的向量,并且 refs_found 到 return 中字符串所在的所有行,我想这样做refs.a 也在 desired_a.
当我尝试这样做时,不出所料,我得到:
Error using strcmp
Inputs must be the same size or either one can be a scalar.
有没有办法不用遍历每一行就可以做到这一点?
您可以使用 ismember
来输入字符串元胞数组,它会输出一个 logical
向量,告诉您字符串元胞数组中的哪些元素出现在源数组。
使用 MATLAB 内置的示例,让我们创建一个 table:
load patients
refs = table(LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic)
现在假设我要查找姓氏为 Jenkins 和 Griffin 的患者。因此:
desired_a = {'Griffin', 'Jenkins'};
refs_found = refs(ismember(refs.LastName, desired_a), :);
您将使用 ismember
访问 table 的行,调用 ismember
时第一个参数是您在 [=34= 中引用的列],第二个参数是你要搜索的字符串。
我们终于得到:
>> refs_found = refs(ismember(refs.LastName, desired_a), :)
refs_found =
LastName Gender Age Height Weight Smoker Systolic Diastolic
_________ ______ ___ ______ ______ ______ ________ _________
'Jenkins' 'Male' 28 69 189 true 134 82
'Griffin' 'Male' 49 70 186 false 119 74
一般来说,首先创建一个包含要搜索的字符串的元胞数组:
desired_a = {'string_1', 'string_2', ...};
之后,使用它索引到您的 table 以获得您需要的内容:
refs_found = refs(ismember(refs.a, desired_a), :);
我知道 matlab 可以方便地从 table 中获取在 'a' 列中具有字符串(在本例中)desired_a 的所有行,如下所示:
refs_found = refs(strcmp(refs.a,desired_a),:);
但是,如果 desired_a 不是字符串,而是带有字符串的向量,并且 refs_found 到 return 中字符串所在的所有行,我想这样做refs.a 也在 desired_a.
当我尝试这样做时,不出所料,我得到:
Error using strcmp
Inputs must be the same size or either one can be a scalar.
有没有办法不用遍历每一行就可以做到这一点?
您可以使用 ismember
来输入字符串元胞数组,它会输出一个 logical
向量,告诉您字符串元胞数组中的哪些元素出现在源数组。
使用 MATLAB 内置的示例,让我们创建一个 table:
load patients
refs = table(LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic)
现在假设我要查找姓氏为 Jenkins 和 Griffin 的患者。因此:
desired_a = {'Griffin', 'Jenkins'};
refs_found = refs(ismember(refs.LastName, desired_a), :);
您将使用 ismember
访问 table 的行,调用 ismember
时第一个参数是您在 [=34= 中引用的列],第二个参数是你要搜索的字符串。
我们终于得到:
>> refs_found = refs(ismember(refs.LastName, desired_a), :)
refs_found =
LastName Gender Age Height Weight Smoker Systolic Diastolic
_________ ______ ___ ______ ______ ______ ________ _________
'Jenkins' 'Male' 28 69 189 true 134 82
'Griffin' 'Male' 49 70 186 false 119 74
一般来说,首先创建一个包含要搜索的字符串的元胞数组:
desired_a = {'string_1', 'string_2', ...};
之后,使用它索引到您的 table 以获得您需要的内容:
refs_found = refs(ismember(refs.a, desired_a), :);