tables/matrix with characters and numbers
Mostrar comentarios más antiguos
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?
Respuestas (3)
Geoff Hayes
el 20 de Dic. de 2014
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
Image Analyst
el 20 de Dic. de 2014
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 comentarios
Image Analyst
el 20 de Dic. de 2014
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.
Azzi Abdelmalek
el 20 de Dic. de 2014
0 votos
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)
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!