Importing CSV - Selecting Specific Variables or Ignoring Variables

22 ビュー (過去 30 日間)
Matt R
Matt R 2021 年 2 月 5 日
回答済み: Nitin Kapgate 2021 年 2 月 8 日
I have the code below to import a CSV file as part of an app I'm building. Initially, I would manually modify some of the CSV files before importing.
The CSV files have data that are pairs of variables (datetime and YVar). I only need one datetime column and want to omit the rest. How would I be able to omit the alternate columns or only accept one datetime column?
Secondly, where I import the Y variables from attach "ValueY" to the variable name. Is there a way I can get Matlab to remove this?
Also, below this section of code, I use the variable names in drop down lists for the user to select for plotting in the app.
I'm using matlab version 2020b.
Thanks!
[file] = uigetfile('*.csv');
if isequal(file,0)
msgbox('Please input a CSV file')
else
isequal(file, 1)
%Read data from file
opts = detectImportOptions([file], "NumHeaderLines", 24, "VariableNamesLine", 1, "VariableNamingRule","preserve");
opts.Delimiter = ",";
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
opts = setvaropts(opts, [1 1], "InputFormat", "dd/MM/yyyy HH:mm");
app.SD = readtable([file], opts);

採用された回答

Nitin Kapgate
Nitin Kapgate 2021 年 2 月 8 日
You can refer to the following code snippet to resolve your problem:
% read an inbuilt spreadsheet
opts = detectImportOptions('airlinesmall_subset.xlsx');
preview('airlinesmall_subset.xlsx',opts)
opts.Sheet = '2007';
% define the variable indices which you want to read
% 2:2:10 ensures that we read alternate columns from the sheet
% Modify the indices as per your requirement
varIndex = [1, 2:2:10]
opts.SelectedVariableNames = varIndex
% Observe selected variables
opts.SelectedVariableNames
opts.DataRange = '2:11';
M = readmatrix('airlinesmall_subset.xlsx',opts)

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Import and Analysis についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by