Effacer les filtres
Effacer les filtres

Find maximum of an array in a for loop?

3 vues (au cours des 30 derniers jours)
Brennan Lytle
Brennan Lytle le 18 Juin 2024
Commenté : dpb le 18 Juin 2024
I need to calculate the maximum of each array from the load variable in the following for loop.
myDir = uigetdir;
myFiles = dir(fullfile(myDir,'*.txt'));
for k = 1:length(myFiles)
baseFileName = myFiles(k).name;
fullFileName = fullfile(myDir, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
num = readmatrix(fullFileName);
load = num(:,1)
ext = num(:,3)
plot(ext,load); hold on
grid on;
end

Réponses (1)

dpb
dpb le 18 Juin 2024
GENERAL GUIDANCE:
Do NOT name a variable load; it is a builtin in important MATLAB function; developing a habit of aliasing it will confuse things immeasruably when come to using .mat files.
myDir = uigetdir;
myFiles = dir(fullfile(myDir,'*.txt'));
N=length(myFiles);
MaxY=zeros(N,1); % preallocate for maxima
for k = 1:N
fullFileName = fullfile(myFiles(k).folder,myFiles(k).name); % use the results directly...
fprintf('Now reading %s\n', fullFileName);
data=readmatrix(fullFileName);
plot(data(:,1),data(:,3));
MaxY(k)=max(data(:,3));
if k==1, hold on; grid on; end
end
No need for copies of the original data just taking up memory...although MATLAB will not make a deep copy here.
  2 commentaires
Brennan Lytle
Brennan Lytle le 18 Juin 2024
Thank you. This worked great!
If I want to find the corresponding row value in column 1 with the maximum found in column 3, how could I add that into the loop?
dpb
dpb le 18 Juin 2024
Read the doc for max -- look at the optional second output variable.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by