How to choose identical values in a cell array with constraints using Matlab?

偶尔善良 提交于 2019-12-01 13:49:53

This may not be an elegant answer, but it is effective:

%The input cell array.
a = cell(4,1);
a{1} = [1 3 1 0];
a{2} = [3 3 3 3];
a{3} = [3 2 3 2];
a{4} = [3 3 3 2];

%The input priority array.
B = [1 1 1 2];

%The output cell array: preallocated for efficiency.
c = cell(size(a));

j = 1;
for i = 1:size(a,1)
%For each i
    if(all(((cell2mat(a(i))==3)&(B==1))==(B==1)))
    %"cell2mat" converts the cell arrays into easily comparable number arrays.
    %"X==Y" for matrices of the same size, will give you a result matrix of the same size with 1 where the values are equal and 0 elsewhere.
    %Thus, "cell2mat(a(i))==3" would compare the number matrices represented by "a{i}" with "3".
    %"(cell2mat(a(i))==3)&(B==1)" would do a logical AND operation with "B==1", that is, "[1 1 1 0]".
    %In short, since you want whereever "a{i}" is 3 when "B" is 1, we want those "a{i}" where the comparison stated above is the same as "B==1".
    %If the result array is the same as "B=1", we get "[1 1 1 1]" as the result of the comparison "((cell2mat(a(i))==3)&(B==1))==(B==1)".
    %The function "all" checks whether the input to it is completely non-zero: here if we get a "[1 1 1 1]" "all" will give us 1, else 0.
        c{j} = a{i};
        %Insert result array into "c" when condition is satisfied.

        j = j + 1;
        %Increment the index of "c".
    end
end


c = c(1:j-1);
%Truncate unused rows of "c".

cell2mat(c)
%Displays the value of "c" as computed.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!