我有一個結構數組,我執行兩次搜索。首先,我搜索特定的顏色,然後搜索特定的城市。我得到了兩個包含我正在查找的數據的數據集。到目前爲止,沒有問題。在MATLAB中找到兩個結構數組的交點
從我得到的兩個數據集中,我想找到兩個數據集中存在於兩個數據集中的結構。
我試過'相交',因爲這似乎是一個很好的選擇數組。但我似乎沒有得到任何相交的數據......爲什麼不呢?
的代碼看起來是這樣的:
%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