How to use if/then to create a vector using values from a table.
조회 수: 1 (최근 30일)
이전 댓글 표시
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
채택된 답변
Voss
2023년 2월 7일
"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
추가 답변 (1개)
Amal Raj
2023년 2월 7일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Denoising and Compression에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!