Create table in a for loop with text

12 views (last 30 days)
Doron Joffe
Doron Joffe on 21 Nov 2021
Commented: Doron Joffe on 24 Nov 2021
I am creating a table in a for loop in Matlab. The table should contain the answer for each iteration of the loop.
On each iteration the, the answer that is produced is the name of a soccer player. I want to create a table that stores the list of the names of soccer players. For example
When I write the below code, it comes out as NaN.
  1 Comment
Image Analyst
Image Analyst on 21 Nov 2021
After you read this:
attach one of your CSV files and your m-file. We cannot run an image and can't run an m-file with no data.
And I think B should be
B = cell(length(files), 1);
before the loop.

Sign in to comment.

Answers (2)

Yongjian Feng
Yongjian Feng on 21 Nov 2021
Edited: Yongjian Feng on 21 Nov 2021
Try this:
files = dir('*.csv');
B = {};
for i = 1:length(files)
csv = readtable(files(i).name, 'Range', 'A1:I8'); % Double check please to make sure
Player = csv(1,2);
Player = table2array(Player) % no ; here, print it out for debug. put it back later
%Player=str2double(Player); % WHY? A player's name can't be converted
%to double
B{end+1} = Player;
T = table(B', 'VariableName', {'Player'})
Doron Joffe
Doron Joffe on 24 Nov 2021
Thank you very much. This worked perfectly.

Sign in to comment.

Sean de Wolski
Sean de Wolski on 23 Nov 2021
Confused as to why you're using excel ranges with csv input. Either way, this should be doable in one shot with readall(datastore).
ds = datastore("*.csv")
ds % MODIFY the settings to only read the (1,2) element. Specify header rows, text type as string, etc.
T = readall(ds)

Community Treasure Hunt

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

Start Hunting!