tables/matrix with characters and numbers

Hi I have a question. I want to create a matrix/table/whatever (lets say 3x4) where I can put character and numbers to have something that look like this:
Italy 100 Cats 2
USA 30 Dog 4
UK 10 M 0
and from this I need to be able to do operations like italy/dogs = 25 how can i do that?

Answers (3)

S - a cell array would allow you to mix the number if with alphabetic data, but trying to access the Italy data and dog data without knowing their indices may be tricky.
Why not use structs? For example,
ctryData.Italy = 100;
ctryData.USA = 30;
ctryData.UK. = 10;
petData.Cats = 2;
petData.Dogs = 4;
petData.M = 0;
then
ctryData.Italy/petData.Dogs
= 25

3 Comments

but if I want to show the table, like the one i did, how can i do that?
Create a cell array of the data or construct a table.
S
S on 20 Dec 2014
Edited: S on 20 Dec 2014
>> valueSet = [327.2, 368.2, 197.6, 178.4];
>> keySet = {'Jan', 'Feb', 'Mar', 'Apr'};
>> table(valueSet,keySet) Undefined function 'table' for input arguments of type 'cell'.
doesn't work the command table.. i don't know why. A friend of mine suggested to use map but with that I have also problem to export the result as a cvs doc.

Sign in to comment.

If you want to use tables, this will work:
% Method using tables.
% Italy 100 Cats 2
% USA 30 Dog 4
% UK 10 M 0
% Create columns
countries = {'Italy'; 'USA'; 'UK'};
col2 = [100; 30; 10]
pets = {'Cats'; 'Dog'; 'M'};
petNumber = [2; 4; 0];
% Assemble tables from the columns.
t1 = table(countries, col2)
t2 = table(pets, petNumber)
% I need to be able to do operations like italy/dogs = 25
% how can i do that?
% Find row index of 'Italy'
col1 = t1(:, 1)
ca = table2cell(col1)
[~, italyIndex] = ismember(ca, 'Italy')
italyRow = find(italyIndex)
% Find row index of 'Dog'
col1 = t2(:, 1)
ca = table2cell(col1)
[~, dogIndex] = ismember(ca, 'Dog')
dogRow = find(dogIndex)
% Do the division.
output = t1{italyRow, 2} ./ t2{dogRow, 2}

2 Comments

S
S on 20 Dec 2014
Edited: S on 20 Dec 2014
I copied and paste your program and I tried to launch it but it doesn't work. Is it possible that the table function doesn't work at all? because i tried also with a basic model from the manual!
Undefined function 'table' for input arguments of type 'cell'.
Error in help (line 11) t1 = table(countries, col2)
Unfortunately you must not have a recent version. To use tables, you must have release R2013b or later. Too bad. Use cell arrays instead like Geoff showed you.

Sign in to comment.

countrie={'Italy' 'USA' 'UK'}'
animal={'Cats' 'Dog'  'M'}'
v1=[100 30 10]'
v2=[2 4 0]'
t=table(countrie,v1,animal,v2)
t.v1(1)/t.v2(2)

Asked:

S
S
on 20 Dec 2014

Commented:

on 20 Dec 2014

Community Treasure Hunt

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

Start Hunting!