1

Suppose I have a cell array containing structs, each with 3 fields.

When I encounter a new struct, I would like to check whether the values in 2 of its 3 fields match those of any struct elements in the array.

cell_array = cell(4,1)
cell_array{1}.Field1 = "ABC"
cell_array{1}.Field2 = 46
cell_array{1}.Field3 = 1648

% Would like to check if fields 1 and 2 match 
% any struct in cell_array
new_struct.Field1 = "ABC"
new_struct.Field2 = 46
new_struct.field3 = 1765

Thank you.

1
  • If your structs all contain the same fields, you should consider using a struct array instead of a cell array of scalar structs. You then index as s(1).Field1. This is more memory-efficient, less error prone, and quite a bit easier to work with. Commented Sep 30, 2018 at 15:23

1 Answer 1

3

You should use Matlab's intersect command. It finds similarities in between two lists of any sort and returns those similarities.

Should then be as simple as:

cell_array = {'ABC', '46', '1648'};

new_array = {'ABC', '46', '1765'};
[C,~,~] = intersect(cell_array,new_array)

disp(C) % C = {'ABC'} {'46'}; 2x1 cell array

% Then simply checking the length of C
if length(C) >= 2
   % Perform your task
end 
Sign up to request clarification or add additional context in comments.

4 Comments

I'm getting an error when I try to run the intersect call, "Input A of class cell and input B of class struct must be cell arrays of character vectors, unless one is a character vector." Is there some issue with the contents of the cell arrays expressed above?
I have updated the way the cell arrays are declared. :=) Unfortunately I do not have access to Matlab from here, but this should work.
Thanks for the feedback. The updated code works as long as the cell contains strings. The challenge I've got is that each element of my cell array is a struct, not a string. And inside those structs are both string and numerical fields. It's those fields that I need to check against.
Ah I see. I misunderstood the question a bit. In that case i would iterate through the elements of each struct using a for-loop and then using the isequal() method instead to evaluate each pair of elements. I can update my answer a bit later to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.