How to perform same operation on 100 different table in single loop

조회 수: 8 (최근 30일)
AL
AL 2022년 12월 13일
편집: Voss 2023년 3월 14일
I have 100 tables name as
Table1
Table2
Table3
..
Table100
and i want to perform same opration on each table; however, length of each table is different but has same number of column that is 2.
how can i perform same opration on each table and store results?
for i = 1:100
Data = Table('num2str('%c')',i);
end
error message:
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched
delimiters.
  댓글 수: 1
Stephen23
Stephen23 2022년 12월 13일
"I have 100 tables name as Table1, Table2, Table3,..Table100"
And that is the start of your problems.
Numbering variable names like that is a sign that you are doing something wrong.
Forcing meta-data (e.g. pseudo-indices) into variable names is a sign that you are doing something wrong.
Now that poor data design will force you into writing slow, complex, inefficient, obfuscated code which is buggy and difficult to debug. Read this to know some of the reasons why:
So far you have not told us how you got all of those variables into the MATLAB worskpace. Presumably you did not sit and write them all by hand... in any case, you should fix your data-design at that point, not by writing bad code later.

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

채택된 답변

Voss
Voss 2022년 12월 13일
for i = 1:100
Data = eval(sprintf('Table%d',i));
% do something with Data ...
end
However, the better solution is not to end up with 100 tables called Table1, Table2, Table3, ...Table100, in the first place.
You can modify the code that gave you those 100 tables, to put them in a cell array instead, e.g., C = {Table1 Table2 ... Table100}.
Then the loop above would be:
for i = 1:100
Data = C{i};
% do something with Data ...
end
and you wouldn't really need the variable Data, you'd just refer to C{i} to use the ith table.
  댓글 수: 2
AL
AL 2022년 12월 14일
Hello,
Thank you so much. the code is working perfectly.
can you please tell me one more thing.
how can i store each table after performing opertaion on it?
right now only Data is overwrtitting everytime when the for loop is running.
Voss
Voss 2022년 12월 14일
편집: Voss 2023년 3월 14일
Assuming you still have 100 tables called Table1, Table2, etc.:
for i = 1:100
Data = eval(sprintf('Table%d',i));
% do something with Data ...
% overwrite Table%d with the new value of Data:
eval(sprintf('Table%d = Data;',i));
end

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by