find difference between 2 colums of a struct in matlab

To find the difference between two columns of a struct in MATLAB, you can use the structfun function to apply a calculation to each field of the struct. Here is an example code:

main.m
% create struct with two columns
s.col1 = [1; 2; 3];
s.col2 = [4; 2; 1];

% calculate difference between col1 and col2
diff = structfun(@(x) x.col1 - x.col2, s, 'UniformOutput', false)

% output:
%     diff =
% 
%       [3×1 double]
% 
%     diff.col1_col2 =
% 
%          3
%          0
%          2
301 chars
18 lines

In this example, the structfun function is used to subtract the col2 field from the col1 field for each element of the struct. The UniformOutput option is set to false to allow the output to be a struct with a field for each calculated field. The resulting diff output is a struct with a single field col1_col2 that contains the resulting column of differences.

gistlibby LogSnag