How to filter only numerical in a table?
Ältere Kommentare anzeigen
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?
Akzeptierte Antwort
Weitere Antworten (1)
Image Analyst
am 7 Feb. 2016
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.
Kategorien
Mehr zu Tables finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!