Read multiple .mat files and process them

조회 수: 3 (최근 30일)
Reza
Reza 2023년 2월 20일
편집: Stephen23 2023년 2월 21일
Hi,
I wanna read some .mat files with name "sub1_hi.mat" to "sub40_hi.mat" that are 4D matrices and process them.
I did the first step with this code:
for j=1:40
load (['s',num2str(j),'_hi_dDTF.mat'])
end
But, when I wanna try this inner loop I got error for the size and imagesc functions.
for j=1:40
data = load (['s',num2str(j),'_hi_dDTF.mat'])
[chan1, chan2, freq, winNumber] = size(data);
for i=1:winNumber
fig = imagesc(data(:,:,3,i))
filename = ['dDTF_s',num2str(j),'_hi_beta',num2str(i),'.jpg']
saveas(fig, filename)
end
end

채택된 답변

Stephen23
Stephen23 2023년 2월 21일
편집: Stephen23 2023년 2월 21일
"As you said in my case the variable's name changes on each iteration of the outer loop."
With changing variable names you will need some complex, fragile code. For example:
for ii = 1:40
F = sprintf('s%d_hi_dDTF.mat',ii);
C = struct2cell(load(F));
assert(isscalar(C),'Only one variable per file!')
data = C{1};
[chan1, chan2, freq, winNumber] = size(data);
for jj = 1:winNumber
fig = imagesc(data(:,:,3,jj));
filename = sprintf('dDTF_s%d_hi_beta%d.jpg',ii,jj);
saveas(fig, filename)
end
end
Better data design would keep the variable names exactly the same on every loop iteration. Then you could write simple, robust code to process that file data. For example, if the variable is always named "data":
for ii = 1:40
F = sprintf('s%d_hi_dDTF.mat',ii);
S = load(F);
[chan1, chan2, freq, winNumber] = size(S.data);
for jj = 1:winNumber
fig = imagesc(S.data(:,:,3,jj));
filename = sprintf('dDTF_s%d_hi_beta%d.jpg',ii,jj);
saveas(fig, filename)
end
end

추가 답변 (1개)

Walter Roberson
Walter Roberson 2023년 2월 20일
The output of load is always a struct that contains one field for each variable that was loaded. Your second code has the right general approach but you need to account for the loaded variable name as a field of data . That is easy enough if the variable name is always the same, but gets a bit messier if the variable names in the files change.
  댓글 수: 2
Reza
Reza 2023년 2월 21일
Thanks, Walter for the answer.
As you said in my case the variable's name changes on each iteration of the outer loop. Can you please give me an example of how this code could work correctly?
Walter Roberson
Walter Roberson 2023년 2월 21일
Use dynamic field names. Compute the name of the variable and use
data.(variablename)
If the variable name is not known then use fieldnames(data)

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

카테고리

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

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by