【问题标题】:Find the intersection of two arrays of structs in MATLAB在 MATLAB 中查找两个结构数组的交集
【发布时间】:2011-09-14 12:32:23
【问题描述】:

我有一个结构数组,我在其中执行两个搜索。首先,我搜索特定颜色,然后搜索特定城市。我得到两个包含我正在寻找的数据的数据集。到目前为止,没有任何问题。

从我得到的两个数据集中,我想找到两个数据集中都存在的两个数据集中的结构。

我尝试过“相交”,因为这对于数组来说似乎是一个不错的选择。但我似乎没有得到任何相交的数据......为什么不呢?

代码如下所示:

%Array of structs
InfoArray(1) = struct  ('Name','AAAA', 'City', 'London', 'Test', '70', 'FavouriteColor', 'red');          
InfoArray(2)= struct('Name','BBBB', 'City', 'London', 'Test', '20', 'FavouriteColor', 'blue');        
InfoArray(3)= struct('Name','CC', 'City', 'London', 'Test', '10', 'FavouriteColor', 'white');        
InfoArray(4)= struct('Name','DD', 'City', 'Stockholm', 'Test', '30', 'FavouriteColor', 'yellow');          
InfoArray(5)= struct('Name','EEEEE', 'City', 'Oslo', 'Test', '15', 'FavouriteColor', 'red');     
InfoArray(6)= struct('Name','FFFF', 'City', 'Oslo', 'Test', '15', 'FavouriteColor', 'red');      
InfoArray(7)= struct('Name','GG', 'City', 'Stockholm', 'Test', '80', 'FavouriteColor', 'blue');           
InfoArray(8)= struct('Name','H', 'City', 'Oslo', 'Test', '60', 'FavouriteColor', 'pink');       
InfoArray(9)= struct('Name','III', 'City', 'Oslo', 'Test', '5', 'FavouriteColor', 'red');      
InfoArray(10)= struct('Name','JJJJ', 'City', 'Stockholm', 'Test', '40', 'FavouriteColor', 'blue');   
InfoArray(11)= struct('Name','KKKK', 'City', 'London', 'Test', '70', 'FavouriteColor', 'white');       




%Find structs in array with color: 'red'

iColor = 'red';
[pFound,matchingFavouriteColors] = findPost(InfoArray,'FavouriteColor',iColor);

%Find structs in array with City: 'London'

iCity = 'London';
[pFound,matchingCity] = findPost(InfoArray,'City',iCity);

%Find the structs that are found in both of the data sets ????
[c, ia, ib] = intersect(matchingFavouriteColors, matchingCity);
disp([c; ia; ib]) 



function [matchFound, matchingData] = findPost(db,sField,iField)
    matches = find(strcmpi({db.(sField)},iField));
    if(isempty(matches))
        disp('No matches found');
        postsFound=0;
    else
        matchingData = db(matches(:));
        matchFound=length(matches);
    end

【问题讨论】:

  • 感谢您为我指明“直接”方向!我倾向于用很多无用的间接来搞乱我的程序。我不得不一次又一次地提醒自己,Matlab 不是 C。我什至没有意识到这可以用逻辑数组来执行。太棒了!

标签: arrays matlab struct intersection


【解决方案1】:

intersect 给你什么错误信息?这应该会提示您为什么它不起作用。

要完成你想要的,你不需要你的 findPost 函数(它的赋值在 postsFound=0; 和一个误导性命名的变量 matchFound,顺便说一句。),你可以使用逻辑索引。

iRed = strcmpi({InfoArray.FavouriteColor},'red');
iLondon = strcmpi({InfoArray.City},'London');
InfoArray(iRed & iLondon)

iRed 包含1s 恰好在颜色为红色的位置,iLondon 位于城市为伦敦的索引处,iRed & iLondon 恰好位于两者都为真的位置——这些逻辑数组可以用作索引到你的结构数组。

编辑:或者,您可以获取数字索引(即find(strcmpi({db.(sField)},iField)) 的结果并在其上使用intersect,获取所需数组元素的数字索引,但是这似乎有点……间接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2012-05-12
    • 2015-12-23
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多