Matlab: добавление двух структур - PullRequest
0 голосов
/ 22 февраля 2012

у меня есть:

A = 

a: 1
b: 2
c: 3
d: 4

B = 

e: 10
d: 10
b: 10
a: 10

Я хочу объединить эти два следующим образом.

new_struct = 

a: 11
b: 12
c: 3
d: 14
e: 10

Порядок полей в 'new' не имеет значения.

Я пытался научиться эффективному программированию на Matlab. Как бы я это сделал, не используя циклы for и if?

Ответы [ 2 ]

1 голос
/ 24 июня 2013

Я предполагаю, что это уже решено, но для всех, кто приходит сюда из Google, вот функция, которая добавит две структуры (хотя и не совсем описанным способом). Он действительно использует для циклов и операторов if, но, надеюсь, он, тем не менее, кому-то пригодится.

function S = addStructs(S1, S2)
% S = addStructs(S1, S2)
%
% Given two structs S1 and S2, returns a struct S such that
% S.<fieldName> = S1.<fieldName> + S2.<fieldName> for all 
% fieldNames whose corresponding values are both numeric
% and the same length in both S1 and S2.
%
% If the values are not numeric or not the same length, the
% value from S1 is copied to S.
%
% This function will throw an error if the field names in
% S1 and S2 are not the same.
%
% Example:
%
% >> s1
% 
% s1 = 
% 
%       a: 1
%       b: 2
%       c: [1 2 3]
%     foo: 'bar'
% 
% >> s2
% 
% s2 = 
% 
%       a: 1
%       b: 4
%       c: 3
%     foo: 'baz'
% 
% >> addStructs(s1, s2)
% 
% ans = 
% 
%       a: 2
%       b: 6
%       c: [1 2 3]
%     foo: 'bar'

fNames1 = fieldnames(S1);
fNames2 = fieldnames(S2);

diff = setdiff(fNames1, fNames2);
if ~isempty(diff)
   error('addStructs: structures do not contain same field names')
end

numFields = length(fNames1);

for i=1:numFields

    % get values for each struct for this field
    fNameCell = fNames1(i);
    fName = fNameCell{:};
    val1 = S1.(fName);
    val2 = S2.(fName);

    % if field non-numeric, use value from first struct
    if (~isnumeric(val1) || ~isnumeric(val2) )
        S.(fName) = val1;

    % if fields numeric but not the same length, use value
    % from first struct
    elseif (length(val1) ~= length(val2) )
        S.(fName) = val1;

    % if fields numeric and same length, add them together
    else
        S.(fName) = val1 + val2;
    end
end

end
0 голосов
/ 22 февраля 2012

Я бы предложил CATSTRUCT и взглянул бы на то, что у Лорен здесь . Я думаю, что вы надеялись на более элегантное решение, но я думаю, что эти методы - то, что сообщество решило.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...