Info

此问题已关闭。 请重新打开它进行编辑或回答。

Creating a cell array

1 次查看(过去 30 天)
Bob Sherland
Bob Sherland 2018-4-25
关闭: MATLAB Answer Bot 2021-8-20
Hi, I was wondering how to create a cell array that will hold two strings and an integer, such that
file_name=input('Please enter the file name: ', 's');
file_author=input('Please enter the file author: ', 's');
no_pages=input('Please enter the number of pages in the file: ');
and the cell array would then become as below with the first two entries as strings and the last entry (no_pages) is a double.
{file_name,file_author,no_pages}
and then how I could add downwards to this so that it would become
{file_name,file_author,no_pages;file_name,file_author,no_pages}
Where the second row is a new file with new information and I can keep adding books into this array in this manner?
Cheers, any help would be appreciated

回答(2 个)

KSSV
KSSV 2018-4-25
N = 10 ;
Books = cell(N,1) ;
for i = 1:N
file_name=input('Please enter the file name: ', 's');
file_author=input('Please enter the file author: ', 's');
no_pages=input('Please enter the number of pages in the file: ');
Books{i} = {file_name,file_author,no_pages} ;
end

Stephen23
Stephen23 2018-4-25
编辑:Stephen23 2018-4-25
Simpler using direct allocation, and does not return nested cell arrays:
N = 10 ;
C = cell(N,3) ;
for k = 1:N
C{k,1} = input('Please enter the file name: ', 's');
C{k,2} = input('Please enter the file author: ', 's');
C{k,3} = input('Please enter the number of pages in the file: ', 's');
end
C(:,3) = str2double(C(:,3));
Using the 's' option does not evaluate whatever input the user gives, and so it much more secure, the str21double simply converts these numbers (as strings) to numeric.

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by