MATLAB: Cell array manipulations in MATLAB

MATLAB

I have two cell arrays: countryname and export.
There is only one column in countryname, which is the code of the names of countries:
USA
CHN
ABW
There are two columns in export:
USA ABW
USA CHN
CHN USA
ABW USA
Each pair (X,Y) in a row of export means "country X has relation with country Y". The size of countryname has been simplified to 3. How can I achieve the following?
Create a square 3 by 3 (in general n by n, where n is the size of countryname) matrix M such that
M(i,j)=1 if country i has relation with country j M(i,j)=0 otherwise.
Here the countrynames are relabeled as positive intergers.

Best Answer

This is as efficient as I can write the code to do what you want:
countryname = { 'USA'
'CHN'
'ABW'};
export = {'USA' 'ABW'
'USA' 'CHN'
'CHN' 'USA'
'ABW' 'USA'};
for k1 = 1:size(countryname)
a(:,:,k1) = cellfun(@times,regexp(export, [countryname{k1}]),repmat({k1},size(export)),'Uni',0);
end
An = sum(cell2mat(a),3);
C = accumarray(An, 1);
fprintf(1, '\t\t %s\t %s\t %s\n', countryname{1}, countryname{2}, countryname{3});
for k1 = 1:size(C,1)
fprintf(1, '\t%s\t%4d\t%4d\t%4d\n', countryname{k1}, C(k1,:))
end
USA CHN ABW
USA 0 1 1
CHN 1 0 0
ABW 1 0 0
How it works:
The first for loop creates cell array ‘a’ with a regexp call inside a cellfun call to find matches and then multiply them by the loop variable at that iteration. (This makes it easier to assign the ‘C’ matrix indices later.) The ‘An’ array creates a (4x2) double array from ‘a’ that is then used by the accumarray call to create indices into array ‘C’ that is the final output array. The second for loop prints the results.