How to find all unique Names in a Matrix

28 ビュー (過去 30 日間)
TDGA
TDGA 2015 年 4 月 10 日
編集済み: Stephen23 2015 年 5 月 22 日
Hello,
I am trying to find all the unique names (Stocks Symbols) contained in the following 7500x7 Cell Matrix. Any suggestion on how to achieve the aimed result? The function ...
unique(Symbol)
does not seem to work.
Thank you

採用された回答

Stephen23
Stephen23 2015 年 4 月 11 日
編集済み: Stephen23 2015 年 5 月 22 日
The fastest choice is to use the backwards compatibility mode of cellfun:
>> A = {NaN,'cath','doug';NaN,'anna',NaN;NaN,'bob','eva';NaN,'anna','cath'}
A =
[NaN] 'cath' 'doug'
[NaN] 'anna' [ NaN]
[NaN] 'bob' 'eva'
[NaN] 'anna' 'cath'
>> unique(A(cellfun('isclass',A,'char')))
ans =
'anna'
'bob'
'cath'
'doug'
'eva'
This simply excludes any non-character values from the unique call, and is faster than calling an anonymous function as the first argument for cellfun:
>> temp(10000)
Elapsed time is 3.403746 seconds.
Elapsed time is 0.096025 seconds.
The timing file is attached here:

その他の回答 (3 件)

Image Analyst
Image Analyst 2015 年 4 月 10 日
This seems to work:
% Create 2 by 3 cell array with 3 unique strings and NaNs.
ca = {nan, 'AAA', 'AAB'; nan, 'AC', 'AAA'}
ca2 = ca(:, 2:3); % Extract columns 2 & 3
% Find the 3 unique strings in columns 2 and 3
uniqueNames = unique(ca2)
What did you do differently?

TDGA
TDGA 2015 年 4 月 10 日
Thank you for the quick reply. Could the problem be caused by the fact that I have NaNs in the Matrix?
Using your example, if I do not execute,
ca2 = ca(:, 2:3); % Extract columns 2 & 3
I do get an error, the very same error I got previously
>> uniqueNames = unique(ca)
Error using cell/unique (line 85)
Input A must be a cell array of strings.
Unfortunately, I ca not just Extract the columns since also in each one of my columns at the end I have NaNs
  1 件のコメント
Image Analyst
Image Analyst 2015 年 4 月 11 日
Then give Jon's suggestion a try.

サインインしてコメントする。


Jon
Jon 2015 年 4 月 10 日
I think the problem is the NaNs. If you don't remove them, as Image Analyst does when defining ca2, the unique function seems to fail. If it's possible for NaN to be dispersed throughout the data, you'll need to exclude them from the unique command. The following might work for you.
UniSyms=unique(Symbol(cellfun(@(x) all(~isnan(x)),Symbol)));

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by