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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by