I want to loop for files in workspace

조회 수: 5 (최근 30일)
Chuchu Debebe
Chuchu Debebe 2022년 5월 12일
댓글: Chuchu Debebe 2022년 5월 13일
Dear all,
I have a lot of data that I imported into my workspace. Let's say I have data1, data2,... and dataN in my workspace. For example, I want to get length(data1), length(data2),... and length(dataN) automatically using a loop. Do I have any way to do that?
  댓글 수: 1
Stephen23
Stephen23 2022년 5월 12일
"Let's say I have data1, data2,... and dataN in my workspace."
And that is the start of your problems: badly-designed data with pseudo-indices forced into the variable names. Accessing numbered variable names in a loop is one way that beginners force themselves into writing slow, complex, inefficient, buggy code that is difficult to debug:
Much better data design would use one array, then you could use simple and efficient indexing, just like MATLAB is designed for.

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

채택된 답변

Stephen23
Stephen23 2022년 5월 12일
"Let's say I have data1, data2,... and dataN in my workspace."
Lets assume that you did not name them all by hand, but instead that you LOADed them one-by-one from some MAT files. In which case, that is the correct place to fix the badly-designed data, e.g. renaming the variable in each MAT file to use exactly the same name, which would make it much easier to write simple, efficient, robust code to process your data.
Remember to always LOAD into an output variable!
If you cannot rename the MAT file vairiables and there is exactly one variable per MAT file, then we can LOAD them like this to avoid having lots of ugly numbered variable names in the workspace:
P = 'absolute or relative path to where the files are saved';
S = dir(fullfile(P,'*.mat'));
N = numel(S);
C = cell(1,N);
for k = 1:N
F = fullfile(P,S(k).name);
C(k) = struct2cell(load(F));
end
V = cellfun(@numel,C)
Simpler and much more efficient than trying to mess around with dynamic variable names.
  댓글 수: 7
Stephen23
Stephen23 2022년 5월 13일
@Chuchu Debebe: fixed now, try it again.
Chuchu Debebe
Chuchu Debebe 2022년 5월 13일
Thank you, sir. It worked!!

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

추가 답변 (1개)

KSSV
KSSV 2022년 5월 12일
s = whos ;
for i = 1:length(s)
s(i).size
end

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by