How can I put the name on above and left side of the matrix?
For example, I have a matrix but there are only numbers (In fact I have more than 100 numbers)
1 5 4 8
1 2 4 8
5 8 9 2
2 6 3 4
If I want to put A, B, C, D, and E on the head and X, Y, Z and N on the left, how can I do that through the code?
It should be:
A B C D E
X 1 5 4 8
Y 1 2 4 8
Z 5 8 9 2
N 2 6 3 4

 Akzeptierte Antwort

Davide Masiello
Davide Masiello am 1 Mär. 2022
Bearbeitet: Davide Masiello am 1 Mär. 2022

0 Stimmen

All elements in an array must be of the same type, i.e. you cannot merge numbers with characters unless you turn the numbers into characters too.
You could do this
A = rand(4,5);
header = ["B" "C" "D" "E" "F"];
fields = ["A" "X" "Y" "Z" "N"];
A = [fields',[header;A]]
Alternatively, take a look at table.

2 Kommentare

Seongyun Kim
Seongyun Kim am 1 Mär. 2022
Thank you for you reply!
However, I have more than 100 numbers. So, do I need to type alphabets 100 times? or is there another way through the code?
Davide Masiello
Davide Masiello am 1 Mär. 2022
What header will you use after you run out of alphabet letters?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Les Beckham
Les Beckham am 1 Mär. 2022
Bearbeitet: Les Beckham am 1 Mär. 2022

0 Stimmen

This is close to what you can do with a table. However, since you only have four columns in your data array, I don't understand why you want labels A through E across the top as column labels (or what is referred to as the VariableNames of a table).
See if this is what you actually want:
A = [1 5 4 8
1 2 4 8
5 8 9 2
2 6 3 4];
array2table(A, 'RowNames', {'X', 'Y', 'Z', 'N'}, 'VariableNames', {'A', 'B', 'C', 'D'})
ans = 4×4 table
A B C D _ _ _ _ X 1 5 4 8 Y 1 2 4 8 Z 5 8 9 2 N 2 6 3 4

Community Treasure Hunt

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

Start Hunting!

Translated by