필터 지우기
필터 지우기

match structures by table

조회 수: 3 (최근 30일)
roblocks
roblocks 2016년 5월 24일
댓글: Guillaume 2016년 5월 24일
Dear All, suppose you have two structures, A and B, where
A.a
A.b
A.c
and
B.1
B.2
B.3
Furthermore you have a table, which matches A to B, for example
1 b
2 a
3 c
bsed on this information, I would like to compute stuff using A and B. Both structures have the same number of fiels (which can all be uniquley matched between A and B). I need something like:
for all *table* rows i:
% computation using A.i, B.i;
end
Is there a good way to solve this in Matlab?
Thanks in advance!

채택된 답변

Stephen23
Stephen23 2016년 5월 24일
편집: Stephen23 2016년 5월 24일
You can do this easily using dynamic fieldnames to access the structures. I do not have a MATLAB version with tables, but this example using a cell array should get you started:
A.a = 1;
A.b = 2;
A.c = 3;
B.x = 4;
B.y = 5;
B.z = 6;
C = {'b','x';'a','y';'c','z'};
out = NaN(size(C,1),1);
for k = 1:size(C,1)
af = C{k,1};
bf = C{k,2};
out(k) = A.(af) + B.(bf);
end
produces the correct result:
>> out
out =
6
6
9
  댓글 수: 2
roblocks
roblocks 2016년 5월 24일
Dear Stephen, yes that works!
For anyone else who is looking for the same thing, here is the code using tables:
clear
A.a = 1;
A.b = 2;
A.c = 3;
B.x = 4;
B.y = 5;
B.z = 6;
C = {'b','x';'a','y';'c','z'}
s1 = {'a', 'b', 'c'}'
s2 = {'x', 'y', 'z'}'
T = table(s1, s2)
out = NaN(size(T,1),1)
for k = 1:size(C,1)
af = C{k,1};
bf = C{k,2};
out(k) = A.(af) + B.(bf);
end
Guillaume
Guillaume 2016년 5월 24일
Or simply:
out = rowfun(@(af, bf) A.(af) + B.(bf), T, 'OutputFormat', 'uniform')

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

추가 답변 (1개)

Guillaume
Guillaume 2016년 5월 24일
Probably the simplest way is to create a function with two inputs, the two field names. Your function then perform the calculation you want using dynamic field names as per Stephen's answer. You use rowfun to iterate over the rows of the table and call your function:
%in its own file (or as an anonymous function)
function result = somefuncname(structA, structB, fieldA, fieldB)
result = structA.(fieldA) + structB.(fieldB);
end
%if using an anonymous function for somefuncname, then you don't need the funwrapper
%pass A and B straight to the function
funwrapper = @(fieldA, fieldB) somefuncname(A, B, fieldA, fieldB);
result = rowfun(funwrapper, yourtable)

카테고리

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