How to use if/then to create a vector using values from a table.

2 views (last 30 days)
Hi, I am new to MatLab and coding in general. Here, I wish to assign a "schoolyear" to each data point. If the table_a.month falls on or after August, schoolyear is equal to the year plus 1. Hence why the code depends on month>=8 (August is the 8th month of the year). The following code gives me the correct values for schoolyear, but is this the proper way to use if/then to create the schoolyear vector? Is there another way you would do it using if/then?
Also two more simple questions: How can I display schoolyear as an 8x1 column in a matrix? And, how can I add schoolyear as a variable to table_a?
Thank you.
table_a = readtable('Data1.xlsx')
table_a = 9×4 table
month day year students _____ ___ ____ ________ 8 7 2000 12 9 8 2000 14 9 9 2000 13 3 11 2001 11 8 3 2001 17 12 15 2001 14 2 2 2002 10 5 1 2002 9 7 3 2002 16
for i = 1:height(table_a)
if table_a.month(i)>=8
schoolyear(i) = table_a.year(i) + 1;
else
schoolyear(i) = table_a.year(i);
end
end
schoolyear
schoolyear = 1×8
2001 2001 2001 2001 2002 2002 2002 2002

Accepted Answer

Voss
Voss on 7 Feb 2023
"is this the proper way to use if/then to create the schoolyear vector? Is there another way you would do it using if/then?"
Looks ok to me, except I would pre-allocate the schoolyear vector (see below).
"How can I display schoolyear as an 8x1 column in a matrix?"
If you want to display schoolyear as a column vector:
schoolyear(:)
If you want schoolyear to be a column vector, one way is to pre-allocate it as such:
table_a = readtable('Data1.xlsx');
% pre-allocate a column vector of zeros:
schoolyear = zeros(height(table_a),1);
% then the loop itself is the same:
for i = 1:height(table_a)
if table_a.month(i)>=8
schoolyear(i) = table_a.year(i) + 1;
else
schoolyear(i) = table_a.year(i);
end
end
% now schoolyear is a column vector containing your values:
schoolyear
schoolyear = 9×1
2001 2001 2001 2001 2002 2002 2002 2002 2002
"how can I add schoolyear as a variable to table_a?"
table_a.schoolyear = schoolyear
table_a = 9×5 table
month day year students schoolyear _____ ___ ____ ________ __________ 8 7 2000 12 2001 9 8 2000 14 2001 9 9 2000 13 2001 3 11 2001 11 2001 8 3 2001 17 2002 12 15 2001 14 2002 2 2 2002 10 2002 5 1 2002 9 2002 7 3 2002 16 2002

More Answers (1)

Amal Raj
Amal Raj on 7 Feb 2023
Hi Macy,
Because it avoids the loop, this is an efficient method of obtaining your desired table.
table_a = readtable('Data1.xlsx');
schoolyear = table_a.year + (table_a.month >= 8)
table_a = addvars(table_a, schoolyear, 'After', 'students', 'NewVariableNames', 'schoolyear');
disp(table_a);

Categories

Find more on Denoising and Compression in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!