Writing a script to create a table based on user input with row names and columns
15 views (last 30 days)
Show older comments
I am writing a script that takes in user input for creating a table, but I cannot seem to find out how to prompt the user for row and column names based on how many rows and columns they select.
The image shows an example of what kind of table I would like to create.
This is what I have so far:
row = input('Enter number of rows: ');
col = input('Enter number of columns: ');
for i = 1:row
promptRow = ['Row ' num2str(i) ' Name: '];
x = input(promptRow, 's');
for j = 1:col
promptCol = ['Column ' num2str(i) ' Name: '];
y = input(promptCol, 's');
str = ['Enter element in row ' num2str(i) ', col ' num2str(j) ': '];
A(i,j) = input(str);
end
end
A;
T = array2table(A,...
'VariableNames',{x},...
'RowNames', {y});
0 Comments
Accepted Answer
KL
on 7 Nov 2017
Edited: KL
on 7 Nov 2017
Do it like this,
row = input('Enter number of rows: ');
col = input('Enter number of columns: ');
A = zeros(row,col);
now before asking the user to input values of the matrix, ask for the row and column names,
rowNames = input('Enter names of rows separated by a space: ',s);
rowNames = strsplit(rowNames);
colNames = input('Enter names of column separated by a space: ',s);
colNames = strsplit(colNames);
for i = 1:row
for j = 1:col
str = ['Enter element in row ' num2str(i) ', col ' num2str(j) ': '];
A(i,j) = input(str);
end
end
then create the table,
T = array2table(A,'VariableNames', colNames,'RowNames', rowNames);
Hope it helps.
4 Comments
KL
on 9 Nov 2017
Oh yes. In the original thread, initially I remember suggesting something like, sum(sum(1:row,1:col)), but anyway, it's all the same. Glad it worked:)
More Answers (0)
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!