Exporting data to excel in matlab

Viewed 655

Hi Im trying to export the results to Excel that I am getting by fprintf inside a loop, I don't know if I'm to use xlswrite or fopen here is the code

names=["Carlos",'Sara','Sinead','Kai','Ali','Chen','Julia','Tom'];
marks= [23,45,67,90,45,61,14,84];
fprintf('Names \t Marks \t Result \n');
for i = 1:length(marks) 
if marks(i) < 39 
   result = ("Fail");
  elseif marks(i) < 69
     result = ("Pass");
  else 
    result = ("Distinction");
  end

   fprintf('%s \t %d \t %s\n',names(i),marks(i),result);
 end

so I'd want fprintf('%s \t %d \t %s\n',names(i),marks(i),result); on excel

1 Answers

Exporting Data as a Table to Excel File

I used an array to record the Results in an array. After evaluating the results of each mark I then create a table using the table() function by inputting the selected arrays to export. Lastly, using the function writetable() allows the table to be exported to a .xlsx Excel file. If you'd like to append to an existing excel file you might have to use an alternative function to open it.

Names =["Carlos",'Sara','Sinead','Kai','Ali','Chen','Julia','Tom']';
Marks = [23,45,67,90,45,61,14,84]';
Results = strings(length(Names),1);

fprintf('Names \t Marks \t Result \n');

for i = 1:length(Marks)
    
  if Marks(i) < 39 
    Results(i) = ("Fail");
   
  elseif Marks(i) < 69
     Results(i) = ("Pass");
     
  else 
    Results(i) = ("Distinction");
  end

   fprintf('%s \t %d \t %s\n',Names(i),Marks(i),Results(i));
end
 

Report_Table = table(Names,Marks,Results);
File_Name = 'Report_Table.xlsx';
writetable(Report_Table,File_Name,'Sheet',1);
Related