How to filter only numerical in a table?
조회 수: 3 (최근 30일)
이전 댓글 표시
Pablo Jaramillo Restrepo
2016년 2월 7일
댓글: Pablo Jaramillo Restrepo
2016년 2월 8일
I have data organized in a column in a table like this:
'1966.csv'
'1967.csv'
'1968.csv'
'1969.csv'
'1970.csv'
'1971.csv'
'1972.csv'
'1973.csv'
'1974.csv'
'1975.csv'
How could I only extract the numerical values (1966, 1967...) and organize them in a column beside the existing one?
댓글 수: 0
채택된 답변
Azzi Abdelmalek
2016년 2월 7일
s={'1966.csv' '1967.csv' '1968.csv' '1969.csv' '1970.csv' '1971.csv' '1972.csv' '1973.csv' '1974.csv' '1975.csv'}
out=cellfun(@(x) str2double(regexp(x,'\d+','match')),s)
댓글 수: 4
Image Analyst
2016년 2월 7일
편집: Image Analyst
2016년 2월 7일
But you accepted the answer. If you want tables instead of cell arrays (like you said), see my answer, which uses tables. You can probably still use Azzi's answer on "FileNames" in my answer, instead of the for loop, but you've got to extract the column of the table into a cell array first, like I did.
추가 답변 (1개)
Image Analyst
2016년 2월 7일
I like that you're using the new variable type of table (well maybe not so new, but since R2013b I think). Tables are a lot easier to use and are more efficient and take up a ton less memory than a cell array.
Here's how to extract the numbers from the first column of your input table, and create a new table that has that original column plus a new column for years.
% Pablo didn't give us the code to create the table variable so we need to do it ourselves.
% First make a cell array of strings"
FileNames = {...
'1966.csv';
'1967.csv';
'1968.csv';
'1969.csv';
'1970.csv';
'1971.csv';
'1972.csv';
'1973.csv';
'1974.csv';
'1975.csv'}
% Now make it into a table with the column named "FileNames"
t = table(FileNames)
OK, NOW we have our table and we can begin:
%==============================================
% Make a new table with the FileNames column,
% PLUS a new column called Year that is the year from the basefile name.
FileNames = t.FileNames; % Extract the first column from t
Years = zeros(length(FileNames), 1); % Preallocate array for column 2.
for row = 1 : length(FileNames)
[~, strYears, ~] = fileparts(FileNames{row}); % Get base file name.
Years(row) = str2double(strYears); % Convert from string to a number.
end
% Now we have years and we can make
% a second, output table from the two column vectors.
t2 = table(FileNames, Years)
Now you have the table you want, in an actual "table"-type variable, rather than a cell array. You could probably construct the Years column vector without a for loop but I thought that way would be easiest for you to understand and follow.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!