How to use if/then to create a vector using values from a table.
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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')
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
0 commentaires
Réponse acceptée
Voss
le 7 Fév 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
"how can I add schoolyear as a variable to table_a?"
table_a.schoolyear = schoolyear
Plus de réponses (1)
Amal Raj
le 7 Fév 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);
0 commentaires
Voir également
Catégories
En savoir plus sur Elementary Math dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!