How to simplify this and make it efficient
조회 수: 4 (최근 30일)
이전 댓글 표시
I have a 1x500 cell (res) with a structure in each, and a 300x3 table (G). I need to check for each combination if strcmp between the field res{j}.fir and each row in G.
If it is equal I need to add the field from res 'thisisstring' to a new 4. column in the table G. The following works but is so slooow....
for i = 1:size(G{:,1},1)
for j = 1:size(res,2)
if strcmp(res{j}.fir,G{i,1}{1})
G{i,4} = res{j}.thisisstring;
end
end
end
If someone have an idea to simplify this it would be great!
댓글 수: 0
채택된 답변
Bruno Luong
2019년 9월 5일
편집: Bruno Luong
2019년 9월 6일
NOTE: what a messy and bad data structure. There might be a much better way than working cell of structs and table.
% Generate test data
S = string(ceil(10*rand(300,3)));
G = table(S(:,1),S(:,2),S(:,3));
fir = num2cell(string(ceil(10*rand(1,500)+5)));
thisisstring = num2cell(string(ceil(100*rand(1,500)+100)));
res = num2cell(struct('fir',fir,'thisisstring',thisisstring));
clear S fir thisisstring % only G and res stay
% Engine here, do the same thing than your double for loops
[b,loc] = ismember( G{:,1}, cellfun(@(r) r.fir, res));
G(b,4) = table(cellfun(@(r) r.thisisstring, res(loc(b)))');
% Check the result
G
댓글 수: 7
Bruno Luong
2019년 9월 6일
편집: Bruno Luong
2019년 9월 6일
I'm not forced, but I don't like to lost my time for something that I can avoid, because I don't like to communicate back/forth with people who asks, gets a solution and discover that it doesn't exactly solve their problem because they failed to give complete details then they are stuck.
This is fortunately not your case, but most of the people who asks are like this.
You should read especially point No. 5
"A common cause for delays in getting an acceptable solution is posting code that doesn't run because it was snipped out of the middle of a program and required variables were assigned in code above that was not included with the Answers post."
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!