find same variablenames in two structures in matlab

To find the same variable names in two structures in MATLAB, you can use the intersect function. Here is an example code:

main.m
% define the two structures
struct1.a = [1,2,3];
struct1.b = 'hello';
struct1.c = 4;

struct2.a = 'world';
struct2.b = [5,6,7];
struct2.c = 8;

% get the common variable names
common_names = intersect(fieldnames(struct1), fieldnames(struct2));
disp(common_names);
264 chars
13 lines

The fieldnames function is used to get the names of all the variables in each structure. The intersect function is used to find the common variable names in both structures. The output of this code will be:

main.m
'c'
4 chars
2 lines

which is the only variable name that exists in both structures.

related categories

gistlibby LogSnag