필터 지우기
필터 지우기

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

조회 수: 6 (최근 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에서 Tables에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by