how to reduce time grabbing values from indices of cell arrays?

조회 수: 1 (최근 30일)
lightroman
lightroman 2017년 11월 7일
댓글: Andrei Bobrov 2017년 11월 7일
I currently do the operation below and wanted to try to do this without a loop since n is very large.
value = 1:5;
results = zeros(n, 5);
for i = 1:n
idx = ismember(tag{i}, value);
results(i, 1:5) = (data{i}(idx))';
end
n is the number of 1xn cell arrays in the multidimensional one.
value can only be a value that exists in all n tag arrays. In this ex it must be 1 through 5.
results is a nx5 matrix of all the data associated with the value found in tag{n}.
tag and data are both multi dimensional cell arrays where size{tag{n}} == size(data{n}), for example:
tag{1} = {1; 2; 3; 4; 5} data{1} = {34; 42; 43; 52; 1}
tag{2} = {1; 2; 3; 4; 5; 6; 7; 8} data{2} = {32; 09; 12; 33; 4; 98; 67; 11}
tag{3} = {1; 2; 3; 4; 5; 6} data{3} = {98; 28; 48; 29; 9; 22}
tag{n} = {1; 2; 3; 4; 5 ...} data{n} = {x1; x2; x3; x4; x5 ...}
results = [34 42 43 52 1;
32 09 12 33 4;
98 28 48 29 9]
Can this be done with cellfun or similar and save time?

채택된 답변

Andrei Bobrov
Andrei Bobrov 2017년 11월 7일
d = [data{:}];
out = reshape(d(ismember([tag{:}],1:5)),5,[])';
  댓글 수: 4
lightroman
lightroman 2017년 11월 7일
hi did you see that tag and data were edited to column vectors? I think just a minor edit fixes, I keep getting dimension mismatches trying to change it.
Andrei Bobrov
Andrei Bobrov 2017년 11월 7일
tag{1} = {1; 2; 3; 4; 5}; data{1} = {34; 42; 43; 52; 1};
tag{2} = {1; 2; 3; 4; 5; 6; 7; 8}; data{2} = {32; 09; 12; 33; 4; 98; 67; 11};
tag{3} = {1; 2; 3; 4; 5; 6}; data{3} = {98; 28; 48; 29; 9; 22};
t = cat(1,tag{:});
t = [t{:}];
d = cat(1,data{:});
d = [d{:}];
out = reshape(d(ismember(t,1:5)),5,[])'

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by