logical index plot specific columns
2 views (last 30 days)
Show older comments
Hi,
I made excel file with date and US dollar spent from 2015 to 2018. I graphed the two columns in excel but I also want to apply same knowledge in MATLAB using logical index. I want to use logical index using string compare to make a new table with each year corresponds with the amount of money spent in that specific year.
here is my first try but not sure why logical index doesn't work.
%%
clc
clear
%%
% read table
data = readtable('SpentinUSDollar.xlsx')
Udate = strcmp(data(:,1),'2015');
tdate = data(Udate,:);
does this work to use logical index? I was thinking to use for loop and the size of the table. Then to make MATLAB to look for 2015 and create table between this year and US Dollar. See the file for more details.
0 Comments
Accepted Answer
Voss
on 20 Apr 2022
%%
clc
clear
%%
% read table
data = readtable('SpentinUSDollar.xlsx','NumHeaderLines',1)
% use curly braces { } to access data from a table;
% parentheses ( ) give you a sub-table
class(data{:,1})
% use year() function to get the year from a datetime array
Udate = year(data{:,1}) == 2015;
% logical indexing to get a sub-table containing data from year 2015
tdate = data(Udate,:)
2 Comments
Voss
on 20 Apr 2022
NumHeaderLines tells readtable how many lines there are in the file above where the data starts. Without setting that to 1, readtable returns this:
data = readtable('SpentinUSDollar.xlsx')
Note that starts with 16-Sep-2015, skipping the first two lines of data from the file.
Using class is unnecessary. I put it there to check the class of the first column of data in the table, the dates. I left it there so you could see the first column is of class datetime.
The year function returns the year of each element of a datetime array:
year(data{:,1})
dt = datetime('2022-04-20')
year(dt)
More Answers (0)
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!