이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
how to average multiple folders with multiple files. I am attaching three folders with two files each. I need a help to find an average of two files from three folders. My code is showing an error"Dot indexing is not supported for variables "
조회 수: 2 (최근 30일)
이전 댓글 표시
MS
2020년 3월 30일
close all
clear all
D = 'D:\filename\';
S = dir(fullfile(D,'*'));
N = setdiff({S([S.isdir]).name},{'.','..'}); % list of subfolders of D.
for ii = 1:numel(N)
T = dir(fullfile(D,N{ii},'*')); % improve by specifying the file extension.
C = {T(~[T.isdir]).name}; % files in subfolder.
for jj = 1:numel(C)
F = fullfile(D,N{ii},C{jj})
fprintf('test%s\n',F);
S(ii).data = F(:);
end
end
Y = cat(3,S(:))%this line is wrong
out = mean(Y,3)
댓글 수: 3
MS
2020년 3월 30일
Thanks. I need two files(test_001.txt, test_002,txt) from all three folders(out of six files) finally. let me know if you need further clarifications.
MS
2020년 3월 30일
code through N(here 3 folders) different folders with M(two files here) different.txt files(text001.txt.....text002.txt) with (O rows and P columns). and find the average(text001.txt.....text002.txt)of M different files from the N folders.
채택된 답변
Ameer Hamza
2020년 3월 30일
Create a script in the same directory where you have folders T1, T2, and T3. Then paste the following code in that script and run it
files = dir('**/*.txt');
data = cell(1, numel(files));
for i=1:numel(files)
filename = fullfile(files(i).folder, files(i).name);
data{i} = readmatrix(filename);
end
M = cat(3, data{:});
average_val = mean(M, 3);
댓글 수: 22
MS
2020년 3월 30일
Thanks for the answer. Your code does the average of all six files all together. But, I need you to help me to get avearge of test_001.txt from all three folders and text_002.txt for all three folders and give it as two diffrent files(avg_value1.txt, averagevalue2.txt.).
Ameer Hamza
2020년 3월 30일
편집: Ameer Hamza
2020년 4월 4일
In that case, try this
files = dir('**/*.txt'); % get names of all the files recursively.
% get the location of current directory to exclude all the files in it
current_dir = pwd;
idx = strcmp(current_dir, {files.folder});
files(idx) = []; % remove the files in current directory from the list
% place all the files with same name in a group
grps = findgroups({files.name});
filegrps = splitapply(@(x) {x}, files, grps');
avg_mat = cell(1,numel(filegrps));
for i=1:numel(filegrps)
grp = filegrps{i};
data = [];
for j=1:numel(grp)
filename = fullfile(grp(j).folder, grp(j).name); % construct the full path of the files
if isempty(data)
data = readmatrix(filename);
else
data = data + readmatrix(filename); % read the matrix and add to previously available values
end
end
avg_mat{i} = data/numel(grp); % calculate the aerage.
end
for i=1:numel(avg_mat)
figure();
axes();
hold on
view(3)
x = avg_mat{i}(:,1);
y = avg_mat{i}(:,2);
u = avg_mat{i}(:,3);
v = avg_mat{i}(:,4);
plot3(x, y, u, '+');
plot3(x, y, v, '*');
legend({'u', 'v'});
writematrix(avg_mat{i}, ['avg_val_' num2str(i)]);
end
Ameer Hamza
2020년 3월 30일
OP's comment moved here:
Many thanks. This code is givng me four files instead of two files for some reason, Can you please check this.
Ameer Hamza
2020년 3월 30일
Check the update code. It will only create 4 files after you run the code 2nd time, because new there are two new txt file. I have updated the code to exclude those files.
MS
2020년 3월 31일
thanks. is there way to save all the average files output as mat files. Sorry, i am asking too much. kindly let me know if you can.
Ameer Hamza
2020년 3월 31일
Yes it can be done by just changing the last for loop
for i=1:numel(avg_mat)
Avg_mat = avg_mat{i};
save(['avg_val_' num2str(i)], 'Avg_mat');
end
Ameer Hamza
2020년 3월 31일
You can add as many line as you want like this:
for i=1:numel(avg_mat)
Avg_mat = avg_mat{i};
name = ['avg_val_' num2str(i)];
writematrix(Avg_mat, name); % .txt
save(name, 'Avg_mat'); % .mat
dlmwrite([name '.dat'], Avg_mat); % .dat
end
Ameer Hamza
2020년 3월 31일
Maybe try this: https://www.mathworks.com/learn/tutorials/matlab-onramp.html. This is a tutorial created by Mathworks and gives a brief overview of basics on MATLAB.
MS
2020년 4월 3일
@Ammer Hamza, I request you to please check and modify the code. The current code is giving the answer as first folder files instead of averaging the three folder files.
Ameer Hamza
2020년 4월 4일
There were a few mistakes in my code. Please check the updated code in the second comment of this answer.
MS
2020년 4월 4일
Many Thanks. you have been really helpful to me. Now, the code works fine. I request you to comment the code. It will be helpful for everyone to learn from your thought process. if you can Please add a code to plot the average output files.
Ameer Hamza
2020년 4월 4일
Please see the updated code. there are four column in your matrix. It will plot each column as a seperate line.
MS
2020년 4월 4일
Thanks for commenting the code . The first two columns of the files are x,y axis and the next two columns are the data. is there a way to mention it in the code and plot it.
MS
2020년 4월 4일
Thanks, plot the figure as mentioned below
first columsn = x axis
second columsn = y axis
third column = u(x,y)
fourth column = v(x,y)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
아시아 태평양
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)