How to concatenate a row of variable names and a double?

7 次查看(过去 30 天)
I want to add my cell array of variable names to a double array of numbers. How would one do this properly?

回答(2 个)

Adam Danz
Adam Danz 2020-8-3
编辑:Adam Danz 2020-8-3
You can concatenate them within a cell array. Based on your question and title, I'm guessing you've got a row of variable names and a row of numbers of equal length to the variable name array.
VarNames = {'Sofia', 'Plovdiv', 'Burgas', 'Varna', 'Veliko Turnovo', 'Haskovo', 'Ruse'};
values = randi(100,size(VarNames));
y = [VarNames; num2cell(values)];
Result:
2×7 cell array
{'Sofia'} {'Plovdiv'} {'Burgas'} {'Varna'} {'Veliko Turnovo'} {'Haskovo'} {'Ruse'}
{[ 82]} {[ 91]} {[ 13]} {[ 92]} {[ 64]} {[ 10]} {[ 28]}
Or perhaps you want a table
T = array2table(values, 'VariableNames', VarNames)
Result: (different random values)
1×7 table
Sofia Plovdiv Burgas Varna Veliko Turnovo Haskovo Ruse
_____ _______ ______ _____ ______________ _______ ____
4 85 94 68 76 75 40

Rik
Rik 2020-8-3
If you want to mix data types: that's not going to be possible. Each variable in Matlab can only be single type, so something like the code below will not work.
['SomeRandomString1' 5;...
'SomeOtherString' pi]
If you want to store an array like that you will need a cell array:
{'SomeRandomString1' 5;...
'SomeOtherString' pi}
Now each cell acts as a container for a variable. In some cells you have now stored char arrays, and in others scalar doubles.

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by