0
votes

I have a structure 1x300 called struct with 3 fields but I'm using only the third field called way. This field is, for each 300 lines, a vertor of index.

Here an exemple with 3 lines to explain my problem : I woud like to search if the last index of the first line is present in an other vector (line) of the field way.

way
[491751 491750 491749 492772 493795 494819 495843 496867]
[491753 491754 491755 491756]
[492776 493800 494823 495847 496867]

I tried with intersect function :

Inter=intersect(struct(1).way(end), struct.way);

but Matlab returns me an error :

Error using intersect (line 80)
Too many input arguments.

Error in file2 (line 9)
Inter=intersect(struct(1).way(end), struct.way);

I don't understand why I have this error. Any explanations and/or other(s) solution(s)?

2

2 Answers

2
votes

Let the data be defined as

st(1).way = [491751 491750 491749 492772 493795 494819 495843 496867];
st(2).way = [491753 491754 491755 491756];
st(3).way = [492776 493800 494823 495847 496867]; % define the data
sought = st(1).way(end);

If you want to know which vectors contain the desired value: pack all vectors into a cell array and pass that to cellfun with an anonymous function as follows:

ind = cellfun(@(x) ismember(sought, x), {st.way});

This gives:

ind =
  1×3 logical array
   1   0   1

If you want to know for each vector the indices of the matching: modify the anonymous function to output a cell with the indices:

ind = cellfun(@(x) {find(x==sought)}, {st.way});

or equivalently

ind = cellfun(@(x) find(x==sought), {st.way}, 'UniformOutput', false);

The result is:

ind =
  1×3 cell array
    [8]    [1×0 double]    [5]

Or, to exclude the reference vector:

n = 1; % index of vector whose final element is sought
ind = cellfun(@(x) {find(x==st(n).way(end))}, {st([1:n-1 n+1:end]).way});
0
votes

You propbably want to use ismember.

Consider what you are passing to the intersect/ismember functions too, struct.way isn't a valid argument, you may need to loop to iterate over each line of your struct (in this case it would be easier to have a cell array, or matrix with equal length rows).

output = zeros(300);
for ii = 1:300
    for jj = 1:300
        if ii ~= jj && ismember(struct(ii).way(end), struct(jj).way)
            output(ii,jj) = 1;
        end
    end
end

Now you have a matrix output where the elements which are 1 identify a match between the last element in way in the struct row ii and the vector struct(jj).way, where ii are the matrix row numbers and jj the column numbers.