Obtaining values from a loop
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
mads skibsted
le 7 Mar 2024
Commenté : Dyuman Joshi
le 11 Mar 2024
How can I store all the data in a matrix from this loop?
for i = 1:size(q,2)
[Maxima(:),MaxIdx(:)] = findpeaks(q(:,i));
[Minima,MinIdx] = findpeaks(-q(:,i));
end
figure; hold on
plot(t(MaxIdx),Maxima,'o');
plot(t(MinIdx),-Minima,'o');
plot(t,q)
4 commentaires
Dyuman Joshi
le 11 Mar 2024
Pre-allocate a cell array and store the values in each iteration - Preallocate arrays, https://in.mathworks.com/help/matlab/matlab_prog/preallocate-memory-for-a-cell-array.html
Réponse acceptée
Rohit Kulkarni
le 11 Mar 2024
Hi Mads,
In my understanding you want to obtain all the information from a matrix using loops.
Here is an example that shows the use of code provided by you on a sample matrix "q" and sample time vector "t":
% Sample time vector
t = linspace(0, 10, 1000); % 0 to 10 seconds, 1000 points
% Sample matrix q with sinusoidal columns of different frequencies
q = [sin(2 * pi * 1 * t); sin(2 * pi * 1.5 * t); sin(2 * pi * 2 * t)]';
% Note: q is transposed to match the expected dimensions (rows are time points)
% Initialize cell arrays to store maxima and minima information
Maxima = cell(1, size(q, 2));
MaxIdx = cell(1, size(q, 2));
Minima = cell(1, size(q, 2));
MinIdx = cell(1, size(q, 2));
% Loop through each column of q
for i = 1:size(q, 2)
[maxima, maxIdx] = findpeaks(q(:,i));
[minima, minIdx] = findpeaks(-q(:,i)); % To find minima
% Store in cell arrays
Maxima{i} = maxima;
MaxIdx{i} = maxIdx;
Minima{i} = -minima; % Convert back to positive values
MinIdx{i} = minIdx;
end
% Plotting
figure; hold on
% Iterate over each column's results to plot
for i = 1:size(q, 2)
plot(t(MaxIdx{i}), Maxima{i}, 'o', 'MarkerEdgeColor', 'r');
plot(t(MinIdx{i}), Minima{i}, 'o', 'MarkerEdgeColor', 'b');
end
plot(t, q) % Plot the original sinusoidal waves
xlabel('Time (s)');
ylabel('Amplitude');
title('Maxima and Minima of Sinusoidal Waves');
legend({'Maxima', 'Minima', 'Waveforms'}, 'Location', 'best');
grid on;
Refer to the following documentation to know more about cell arrays:
Hope this resolves your query!
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!