Need help creating a table in which each cell contains a pair( or more) of numbers

3 views (last 30 days)
Hello, I need some help with creating a specific table within matlab. I'm not sure how to do it, but I would like my data to be organized like so:
x:
1 2 3 4 5
y:
1 (5,7) ....
2
3
4
5
Also, I would like to be able to label the "x" and "y", and also the values of x and y. Thanks.

Answers (2)

Marc Jakobi
Marc Jakobi on 5 May 2015
Use a cell array. You could run the following code:
xlab = {[], '1', '2', '3', '4', '5'}; %labels as strings, comma to make a row cell
ylab = {[]; '1'; '2'; '3'; '4'; '5'}; %semicolon to make a column cell
%leave an empty brackets at the beginning
data = cell(length(ylab),length(xlab));
data(1:length(ylab),1) = ylab;
data(1,1:length(xlab)) = xlab;
Now you just need to index the cell to put your data in. So if you want to put the vector [5, 7] in the position of your example, you could index it like this, using {} for the coordinates
xy = [5, 7]; %vector
data{2,2} = xy; %data{y+1,x+1} = vector
Note that the x & y coordinates have to have 1 added to them for indexing, because of the x & y labels taking the places of the first indexes...
Hope this helps :)

Stephen23
Stephen23 on 5 May 2015
Edited: Stephen23 on 5 May 2015
Planning your data structure well is half of the work done writing your code. Although cell arrays are great, if you do not need to use them then they only make indexing and operations more complicated. If you keep all of your data in a simple numeric array then you can use all of MATLAB's code vectorization strengths, which is faster and neater than trying to access data in cells using loops.
Often it is easier to use the dimensions of the array to store your data, which may seem unintuitive if you come from some other programming languages where lists and nested data is more commonly used to structure data, but this is a fast and powerful method of storing data in MATLAB. Do not think of nesting data in cells (unless you really must), rather think of how you can use the dimensions of an array to structure your data.
In practice this means you could access the data like this:
A(1,1,:) = [5,7];
Also note that MATLAB numeric data types do not contain any meta-data such as names, titles, units, etc. In MATLAB it is usual to store meta-data separately in another numeric/cell array. If you really do want them in the same data variable, then you can use tables.

Categories

Find more on Cell Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!