MATLAB: How to divide matrix in submatrix

matrixsubmatrix

Problem: I have the matrix 'matlab' (attached): colums 1 are locationId, columns from 2 to 4 are dates (year, month, day) and colums 5 are labels. I want to obtain a matrix in which I have, for every date, locationId and labels: for example fist and second colums have locationId and labels corrisponds to the first date (2004/8/3), third and fourty colums have locationId and labels corrisponds to the second date (2004/8/4), etc. Can you help me?
I have an other problem correlate to this: I have a struct A that contains SemanticTraj (LocationId, date, label) for 106 users. I find with your code locationId and labels for the first six users (i use only six to text) and save them in a struct, respectively in semanticTrajCompact(1,k).locID and semanticTrajCompact(1,k).labNm. I want to trasform the values in semanticTrajCompact(1,k).labNm in strings: I apply num2str but the code instead trasform all the rows in strings, change only the last. I don't understand why, can you give me some suggestions? The code is
load('A.mat')
nCols=6;
% create a struct to memorize values
semanticTrajCompact(nCols)=struct('locID',[],'labNm',[],'semanticTrajStr',[],'semanticTrajCompact1',[],'semanticTrajCompact2',[]);
for k=1:6
if ~isempty(semanticTraj(1,k).semanticTraj)
% for every day, find locID e label
[D,~,X] = unique(semanticTraj(1,k).semanticTraj(:,2:4),'rows');
semanticTrajCompact(1,k).locID = accumarray(X,semanticTraj(1,k).semanticTraj(:,1),[],@(v){v});
semanticTrajCompact(1,k).labNm = accumarray(X,semanticTraj(1,k).semanticTraj(:,5),[],@(v){v});
end
if ~isempty(semanticTrajCompact(1,k).labNm)
% transforms columns of semanticTrajCompact.labNm in strings
for i=1:size(semanticTrajCompact(1,k).labNm,1)
semanticTrajCompact(1,k).semanticTrajStr=num2str(semanticTrajCompact(1,k).labNm{i,:}');
end
end
end

Best Answer

Here is some code that takes your matrix a (contained in the mat file matlab) and efficiently concatenates the location IDs and label numbers for each date:
>> S = load('matlab');
>> [D,~,X] = unique(S.a(:,2:4),'rows');
>> locID = accumarray(X,S.a(:,1),[],@(v){v});
>> labNm = accumarray(X,S.a(:,5),[],@(v){v});
Both locID and labNm are cell arrays, each cell corresponding to a row of D (i.e. the dates in the same order). I have not merged the numeric arrays in the cells into one single numeric array as the numeric arrays have different numbers of elements.
Accessing the data is very easy, for example the third date is:
>> D(3,:)
ans =
2004 8 3
and the corresponding (third) location IDs are:
>> locID{3}
ans =
641
661
641
661
642
.. etc
and similarly for the label numbers:
>> labNm{3}
ans =
2
4
4
4
4
4
..etc