How to store value in the table using looping

조회 수: 19 (최근 30일)
Yew Jen Chong
Yew Jen Chong 2022년 6월 22일
댓글: Yew Jen Chong 2022년 6월 24일
Hi,
I want to store data in a table using looping. I am trying to store all the value of each iteration in the table but it can only store the values of the last iteration. The coding below is what I tried.
for n = 1:3
Table.Data_A = DataA;
Table.Data_B = DataB;
Table.Data_C = DataC;
Table(n,;) = Table;
end
I will appreciate if someone can help me.
Thank you.

채택된 답변

Karim
Karim 2022년 6월 22일
편집: Karim 2022년 6월 23일
hello, below you can find an example on how to store data in a table in a loop
numLoop = 10; % indicate the number of loops...
numCol = 3; % indicate the number of columns for the table...
% generate some random data
DataA = 1:numLoop;
DataB = rand(numLoop,1);
DataC = ["A","B","C","D","E","F","G","H","I","J"];
% allocate the table
varTypes = ["double","double","string"]; % data type for each column
varNames = ["DataA","DataB","DataC"]; % variable name for each column
MyTable = table('Size',[numLoop numCol],'VariableTypes',varTypes,'VariableNames',varNames);
% perfom the loop
for n = 1:numLoop
% store data in the table
MyTable(n,:) = {DataA(n), DataB(n), DataC(n)};
end
% display the result
MyTable
------------------------------------------------------------------------------------------------------------------------------------------------------
Edit: next to the orginal example, i also added modified the code with the later added example data and script, see attachment
@Yew Jen Chong: the code is to slow to run here, however below you can find the print screens of the result run locally (the code is in attachement)
and the remainder of the table...

추가 답변 (1개)

Yew Jen Chong
Yew Jen Chong 2022년 6월 23일
Hi @KASR,
There are some errors when I tried on my side. Would you like to help me correct my mistake?
I have attached the files.
Thank you so much for your help.
  댓글 수: 1
Karim
Karim 2022년 6월 23일
see the changes to the original answer, you can comment there ;) No need to create a new 'answer'

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by