在 MATLAB 中找到两个结构体数组的交集

3
我有一个结构体数组,在其中执行两次搜索。首先,我搜索特定的颜色,然后我搜索特定的城市。我得到了两个包含我要查找的数据的数据集。到目前为止,没有问题。
从这两个数据集中,我想找到同时存在于两个数据集中的结构体。
我尝试使用“intersect”,因为它似乎是处理数组的好方法。但是我好像没有得到任何交集数据……为什么呢?
代码看起来像这样:
%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语言。我甚至没有意识到这可以通过逻辑数组来实现。太神奇了! - Gunilla
1个回答

3
intersect 给你什么错误信息?这应该可以给你一个提示,为什么它不能工作。
为了实现你想要的,你不需要 findPost 函数(它在 postsFound=0; 处有一个无用的赋值和一个具有误导性的命名变量 matchFound)。你可以使用逻辑索引。
iRed = strcmpi({InfoArray.FavouriteColor},'red');
iLondon = strcmpi({InfoArray.City},'London');
InfoArray(iRed & iLondon)

iRed包含红色的位置为1iLondon包含伦敦城市的索引,iRed & iLondon包含两者都为真的逻辑数组--这些逻辑数组可以用作您的结构数组的索引。

编辑:或者,您可以获取数值索引(即find(strcmpi({db.(sField)},iField))的结果),并在它们上使用intersect,得到您想要的数组元素的数值索引,但这似乎有点...间接。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接