How do you add a header to a matrix?

I currently use 'fprintf' function on a line before i want to display my matrix but I feel like there is a better way to do it that I am unaware of.

Answers (2)

Well, you could make the variable a table (if you have R2013b or later). Then it will put a header line automatically in the command window when you display it.
From the help:
LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
T = table(Age,Height,Weight,BloodPressure,...
'RowNames',LastName)
In the command window:
T =
Age Height Weight BloodPressure
___ ______ ______ _______________
Smith 38 71 176 124 93
Johnson 43 69 163 109 77
Williams 38 64 131 125 83
Jones 40 67 133 117 75
Brown 49 64 119 122 80

5 Comments

I coppied and pasted this code and it did not work.
@James Young I copied and pasted the code and it did work, in r2021a, about a dozen releases after the answer was written. Could you be more specific about what you mean it didn't work? Are you using a much older release of Matlab? Did you get an error message? Did something unexpected happen?
@Adam Danz i am using hte r2020b I believe, but I coppied and pasted exactly what you commented and it returned the error:
Unable to use a value of type cell as an index.
Error in exam2_CME220_2019 (line 68)
T = table(Age,Height,Weight,BloodPressure,...
also I found a better way to do it using the code:
array2table(table, 'VariableNames', {'column 1', 'column 2', 'column 3', 'column 4'})
There is no indexing in this answer, though.
I believe your error is that you have a variable named "table" which is a function name in this answer.

Sign in to comment.

Geoff Hayes
Geoff Hayes on 14 Feb 2015
Nicholas - if you just want to write a blank line (or header) before writing out your matrix, then using fprintf('\n'); is the correct way to do this.

Categories

Tags

Asked:

on 14 Feb 2015

Commented:

on 14 Apr 2021

Community Treasure Hunt

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

Start Hunting!