MATLAB Answers

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

2 views (last 30 days)
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'

  0 Comments

Sign in to comment.

Accepted Answer

David K.
David K. on 7 Aug 2019
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 Comments

David K.
David K. on 7 Aug 2019
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 on 6 Dec 2019
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

Sign in to comment.

More Answers (0)

Sign in to answer this question.