extracting unique numbers from a cell array

조회 수: 3 (최근 30일)
Milos
Milos 2023년 3월 1일
댓글: Star Strider 2023년 3월 1일
Hi, I am trying to extract the unique values from a cell array whose entries are vectors of unspecified length.
To be more precise I have a 10x10x10 cell arrray, call it G and each cell is empty or contians a vector of some unspecfied length. What I would like to do is obtain the unique list of entries of the vectors that have at least length 2.
For example if
G{1} = [1]
G{2} = [1]
G{3} = [2,3,4]
G{4} = [4,5]
and all the other cells are empty then the output would be [2,3,4,5].
What I have so far is
G = grid(U,d,k); %Grid is a built in function that returns a 10x10x10 cell array
H = find(~cellfun('isempty', G));
h = length(H);
counter = zeros(1,h);
for i = 1:h %find all the cells in G that contian at least two values
if length(G{H(i)}) >=2
counter(1,i) = H(i);
end
end
newcounter = nonzeros(counter); %all array positions in array that have vectors of at least length two
GG = G(newcounter); % collection of cells in G whose vectors are at least two
I'm trying to find a function or an efficent way do this. I have tried concatenating GG and apply unique also I have seem the follwoing suggestion which is to try unique(cellfun(@num2str,G,'uni',0)). This to also fails since I just get GG with all the duplicated cells removed.

채택된 답변

Star Strider
Star Strider 2023년 3월 1일
One approach —
G{1} = [1];
G{2} = [1];
G{3} = [2,3,4];
G{4} = [4,5];
Len2 = cellfun(@(x)numel(x)>=2, G)
Len2 = 1×4 logical array
0 0 1 1
Gu = unique([G{Len2}])
Gu = 1×4
2 3 4 5
I am not certain how robust this will be to your larger cell array. It works in the provided example.
.
  댓글 수: 2
Milos
Milos 2023년 3월 1일
Thansk this works great! I have yet to test anything with larger values
Star Strider
Star Strider 2023년 3월 1일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by