The aim of this question is to learn how to use structure arrays in MATLAB and e
ID: 671500 • Letter: T
Question
The aim of this question is to learn how to use structure arrays in MATLAB and export
the information into an Excel spreadsheet.
[8 marks] Write a script named ‘structArrayQ3.m’ which creates a structure array (called StudentRecord) that takes a number of fields such as student_name, student_id, marks on a number of units, and the total marks.
[12 marks] Use the sample.txt file as the data source file. Each line in this file is separated by newline. The first two lines are integers – the 1st integer (N) represents the number of students and the 2nd integer (M) represents the number of subjects that a student has taken. From this point onward there are N records for N students. The fields are (in order) student_id, student_first_name, student_last_name, M marks for M subjects. Read the data from the file, calculate the total marks for each student, and populate them in to the structure array (StudentRecord).
[10 marks] Export the information in the structure array (StudentRecord) to an Excel file
Explanation / Answer
fid = fopen('data.txt','r');
tline = fgetl(fid);
flds = regexp(tline,'s*','split');
% initialize the first prototype struct
data = struct();
for ii=1:length(flds)
data.(flds{ii}) = [];
end
ii = 1;
% get the first line of data
tline = fgetl(fid);
while ischar(tline)
% parse the data
rowData = regexp(tline,'s*','split');
for jj=1:length(flds)
data(ii).(flds{jj}) = rowData{jj};
end
tline = fgetl(fid);
ii = ii + 1;
end
fclose(fid)
field = 'f';
value = {'some text'; [10, 20, 30];magic(5)};
s = struct(field,value);
field1 = 'f1'; value1 = zeros(1,10);
field2 = 'f2'; value2 = {'a', 'b'};
field3 = 'f3'; value3 = {pi, pi.^2};
field4 = 'f4'; value4 = {'fourth'};
s = struct(field1,value1,field2,value2,field3,value3,field4,value4);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.