Extracting values from a cell array into new arrays
5 views (last 30 days)
Show older comments
Hi,
I have a 1x44 cell array where each column contains a 72x4 double array. I also have a 10x2 double array. Please see both .mat files attached if further clarification is needed regarding the structure. I am referencing the values in these mat. files in my problem as follows:
I need to extract the double arrays in the 1x44 cell array referenced in the first column of the 10x2 double array into a new cell array. So the first double array extracted for instance would be the 4th column of the cell array.
The second thing I want to do is then extract from the second column of each double array of the new cell array the value referenced in the second column of the 10x2 double array. I would like all rows adjacent to also be extracted. For instance the first values would all be within row 5 of the first double array of the new cell array.
Any suggestions on how to do these two steps would be most welcome.
0 Comments
Accepted Answer
Andrei Bobrov
on 26 Dec 2019
Edited: Andrei Bobrov
on 27 Dec 2019
CC = cat(3,C{:});
[m,n,k] = size(CC);
Z = permute(repmat(b,1,1,n),[1,3,2]);
out = CC(sub2ind([m,n,k],Z(:,:,2),repmat(1:n,size(b,1),1),Z(:,:,1)));
or
n = cellfun('size',C,1);
i = repelem((1:numel(n))',n(:));
CC = cat(1,C{:});
out = CC(ismember([i,CC(:,2)],b,'rows'),:);
in your case
CC = cat(1,C{:});
out = CC(ismember(CC(:,1:2),b,'rows'),:);
0 Comments
More Answers (1)
Stephen23
on 26 Dec 2019
Edited: Stephen23
on 26 Dec 2019
Step 1: indexing:
D = C(b(:,1));
Step 2: cellfun and an anonymous function:
F = @(m,v)m(m(:,2)==v,:);
Z = cellfun(F,D(:),num2cell(b(:,2)),'uni',0);
W = cell2mat(Z) % optional
Giving:
W =
4 5 2.4181 0.43232
8 63 2.7632 0.44257
12 45 3.7255 0.41266
20 3 5.3249 0.11164
24 22 1.4465 0.30058
28 18 3.1631 0.58063
31 71 2.0108 0.2431
33 66 1.0293 0.38437
36 50 1.7156 0.36392
43 2 2.0634 0.14015
Checking the first row by hand:
>> b(1,1)
ans =
4
>> T = C{4};
>> T(T(:,2)==b(1,2),:)
ans =
4 5 2.4181 0.43232
0 Comments
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!