How to find specific values in a table, and create an array from rows containing those values?

13 ビュー (過去 30 日間)
Imagine that what is below is part of the table I am working with. The letters are the markers for certain experimental events, and the numbers are the times. What I want to know is what is the best way to find the rows where the second column is 'SSRP' for example, and then create an array from that. (or just make another table and then do table2array). So the end result would be separate arrays with all the times for the different event markers SSRP, TGHH, etc etc.
453001 'SSRP'
462419 'SSRP'
473639 'SSRP'
513555 'SSRP'
528685 'SSRP'
239175 'TGHH'
246893 'TGHH'
252401 'TGHH'

採用された回答

David K.
David K. 2019 年 8 月 7 日
Here is my go at it.
% Create my table so you know what I am testing with.
names = {'ssrp' , 'ssrp','tghh'}';
values = [123, 954, 1324]';
myTab = table(values,names,'VariableNames',{'values','names'});
nameList = unique(myTab.names); % Get all the unique labels
for n = 1:length(nameList)
Eventtimes{n} = tab.values(strcmp(tab.names,nameList{n}));
end
This results in 1 variable with a different matrix in each cell corresponding to the different events. Let me know if you need it in a different format and want help with it. May be hard to convert to a table since I believe columns need to be the same size.
  3 件のコメント
David K.
David K. 2019 年 8 月 7 日
Not sure what you mean but this is the base form I used in my answer. I used the second one as an add-on to the first line.
T = table(var1,...,varN)
T = table(___,'VariableNames',varNames)
Adam Danz
Adam Danz 2019 年 12 月 6 日
Note that this can be reduced to two lines.
% Create the input table
data = {
453001 'SSRP'
462419 'SSRP'
473639 'SSRP'
513555 'SSRP'
528685 'SSRP'
239175 'TGHH'
246893 'TGHH'
252401 'TGHH'};
T = cell2table(data,'VariableNames',{'values','names'});
% Create value list for each unique name
unqNames = unique(T.names);
EventTimes = arrayfun(@(i)T.values(strcmp(T.names,unqNames{i})),1:numel(unqNames),'UniformOutput',false);
In the loop-method above, don't forget to pre-allocate your loop variabels.
Eventtimes = cell(size(nameList)); % <--- ADD THIS
for n = 1:length(nameList) % <--- Also numel() is safer than length()
Eventtimes{n} = tab.values(strcmp(tab.names,nameList{n})); % <--- 'tab' should be myTab
end

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by