Create table in a for loop with text

조회 수: 7 (최근 30일)
Doron Joffe
Doron Joffe 2021년 11월 21일
댓글: Doron Joffe 2021년 11월 24일
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
Player
Ronaldo
Messi
When I write the below code, it comes out as NaN.
  댓글 수: 1
Image Analyst
Image Analyst 2021년 11월 21일
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.

댓글을 달려면 로그인하십시오.

답변 (2개)

Yongjian Feng
Yongjian Feng 2021년 11월 21일
편집: Yongjian Feng 2021년 11월 21일
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;
end
T = table(B', 'VariableName', {'Player'})
  댓글 수: 2
Peter Perkins
Peter Perkins 2021년 11월 23일
편집: Peter Perkins 2021년 11월 23일
This
Player = csv(1,2);
Player = table2array(Player)
can't be the best way to do this. More than likely
Player = csv{1,2};
or (much) better yet:
Player = csv.Player(1) % or whatever column heading is in the file
Doron Joffe
Doron Joffe 2021년 11월 24일
Thank you very much. This worked perfectly.

댓글을 달려면 로그인하십시오.


Sean de Wolski
Sean de Wolski 2021년 11월 23일
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)

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by