MATLAB: Breaking up a matrix/array

indexingmatrix manipulation

I am running a regression of some global equity data over various style factors, however my return data is conglomerated into one 30,000×2 matrix….One column is the "country code) of the security and the other is the return(obviously). Is there a way to break up this returns matrix into many smaller matrices based on the country.I thought about using a for loop with an if statement like: for i = 1:length(country_codes) if country_codes(i) == country_codes(i+1)
And then I get stuck….it doesnt seem reasonable to use a for loop where I will be creating a new matrix inside the loop, possily breaking out of the loop to store the matrix, and then starting where I left off. There are about 50 countries, so you can see how this would be terribly inefficient (if at all possible). Also, ideally I would store the indices of the new arrays of country codes so that I could use these indices to concatenate the new country code and return arrays with the corresponding style factor weights and industry code data for the regression. Hopefully someone has a good idea! Thanks!

Best Answer

codes = matrix(:,1);
code_list = unique(codes);
for i = 1:numel(code_list)
new{i} = matrix(code_list(i) == codes,:);
end