简体   繁体   中英

Matlab - How to compare values in a cell array?

I have a set of inputs and one output declared in a cell array like that:

A = {'a', 'f', 'c', 'b';
     'b', 'f', 'c', 'a';
     'a', 'f', 'b', 'c';
     'c', 'f', 'b', 'a';
     'c', 'f', 'a', 'b';
     'b', 'f', 'a', 'c' }

where the first column is an output, and the rest are the inputs used, for each output.

I need to compare the values to reduce the calculation time. So, the thing is, for equals outputs, I wanna know if the inputs are the same, a important remark.. the order of values desn't metter, so, when comparing fcb with fbc it is the same.

I need this because, acttualy, my data set is a 5040 x 7 cell array and I need to put them into a intorpolation function.

I thought in something like

if the value of the output column is equal to the another value of the same column, check if the value of inputs are all the same, using, ismember function. But I can not arrive to a code that works.

Any help, please?

First, since you don't care about the order of the inputs, I would sort each of the rows:

[T, N] = size(A);
for t = 1:T
  Asorted(t,1)   = A(t,1);
  Asorted(t,2:N) = sort(A(t,2:N));
end

Now you want to find all of the duplicate rows. A simple way to do this is first to convert to a character array, and use the unique function --

B = cell2mat(Asorted);
[C, ii, jj] = unique(B,'rows');

Now C contains the unique rows of B , ii contains the indexes of the unique rows, and jj labels each of the rows of B depending on which unique value it has.

If you wanted to filter out all of the duplicate rows from A , you can now do

Afiltered = A(ii, :);

This results in:

Afiltered = 
    'a'    'f'    'b'    'c'
    'b'    'f'    'a'    'c'
    'c'    'f'    'a'    'b'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM