필터 지우기
필터 지우기

Allocating 500 matrices into one 3D array with a loop

조회 수: 1 (최근 30일)
Zoe
Zoe 2017년 11월 19일
댓글: Zoe 2017년 11월 20일
Hello guys, I have about 500 matrices naming after "yfit" + yr/month/date (such as yfit20000115). I want to save all of them into one 3d array, here is my code:
x = zeros(1455,1464,500);
x(:,:,1) = yfit20000115;
x(:,:,2) = yfit20000131;
x(:,:,3) = yfit20000216;
x(:,:,4) = yfit20000303;
x(:,:,5) = yfit20000319;
x(:,:,6) = yfit20000404;
........................ until x(:,:,500)
Can anybody please tell me how to loop through this? Especially, I do not know how to put the names into the loop. I thought about using EVAL, but eval's instruction on matlab seems very short and simple. Please help, thank you!
  댓글 수: 4
Stephen23
Stephen23 2017년 11월 20일
편집: Stephen23 2017년 11월 20일
@Zoe: simply load the .mat file into one output variable (which is a structure), then loop over the fields of that structure. See Nicolas Schmit's answer to know how to do this.
Do NOT load 500 individual arrays into your workspace and then try to use eval to access them, unless you want to write slow, buggy, complex, inefficient, hard-to-debug code. Read this to why doing that is a very inefficient way to write code:
Zoe
Zoe 2017년 11월 20일
@Stephen Cobeldick: Thank you so much for telling me this! I read through the link and also sent the link to my professor!

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

채택된 답변

Nicolas Schmit
Nicolas Schmit 2017년 11월 20일
Use
S = load('your_mat_file');
To load your data into a structure S, Then loop over the fields of S.
fields = fieldnames(S);
x = zeros(1455,1464,500);
for k=1:500
x(:, :, k) = S.(f{k});
end
  댓글 수: 2
Jan
Jan 2017년 11월 20일
Or:
S = load('your_mat_file');
fields = fieldnames(S);
[fields, index] = sort(fields);
match = strncmp(fields, 'yfit', 4);
dataCell = struct2cell(S);
x = cat(3, dataCell{index});
Zoe
Zoe 2017년 11월 20일
I want to say thank you to both of you for being so helpful!!

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

추가 답변 (0개)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by